2016-11-23 4 views
1

Я начинаю с Vue.js, и я хотел бы обновить родительские данные после завершения ajax в компоненте. Проблема в том, что я использую фильтр moment, без фильтра все отлично, но мне нужен этот фильтр. Первый рендеринг без проблем, потому что столбец resolved_date пуст. Но после того, как Ajax называют данные и вылетают из компонента к родителю, я хочу, чтобы обновить родительские данные (resolved_date), но я получаю ошибку:Vue.js - обновить родительские данные с помощью фильтра

vue.js:2611 [Vue warn]: Property or method "moment" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in root instance) 

До сих пор у меня есть:

Edit: вот это JS Bin example с той же ошибкой.

<div id="container"> 
    <table border="1"> 
     <template v-for="(difference, index) in storage.differences"> 
      <tr> 
       <td rowspan="2" is="repair-btn" :diff="difference" :index="index"></td> 
       <td rowspan="2">{{ difference.sn }}</td> 
       <td rowspan="2">{{ difference.resolved_date ? (difference.resolved_date | moment) : null }}</td> 
       <td>{{ difference.source }}</td> 
      </tr> 
      <tr> 
       <td>{{ difference.pair.source }}</td> 
      </tr> 
     </template> 
    </table> 
</div> 

<template id="repair-btn"> 
    <td> 
     <button @click="repairDifference">fix</button> 
    </td> 
</template> 

<script> 
    Vue.filter('moment', function (date) { 
     return moment(date).format('DD.MM.YYYY HH:mm:ss'); 
    }); 

    new Vue({ 
     el: '#container', 

     data: { 
      storage: { 
       differences: [ 
        {sn: 111, resolved_date: null, source: 'EK', pair: {source: 'VLT'}}, 
        {sn: 222, resolved_date: null, source: 'EK', pair: {source: 'VLT'}} 
       ] 
      }, 
     }, 

     mounted() { 
      this.$root.$on('updateEvent', function (data, index) { 
       this.storage.differences[index].resolved_date = data; 
       console.log(this.storage.differences[index].resolved_date); 
      }) 
     }, 

     components: { 
      repairBtn: { 
       template: '#repair-btn', 
       props: ['diff', 'index'], 

       methods: { 
        repairDifference: function() { 
         this.diff.loading = true; 
         this.$http.post('/path.file.php', { 
          ids: this.diff.id 
         }).then(function (response) { 
          this.$root.$emit('updateEvent', '2016-01-01 00:00:00', this.index); 
         }).catch(function (error) { 
          console.log(error.data); 
         }); 
        } 
       } 
      }, 
     }, 
    }); 
</script> 

Как я могу обновить данные с помощью фильтра без каких-либо ошибок?

ответ

1

Фильтры не работают в этом случае, потому что вы хотите использовать их в тройном выражении. (В настоящее время, вы будете делать сравнение побитовое | с this.moment, который не установлен, поэтому вы получите предупреждение.).

Вы можете просто использовать метод вместо:

methods: { 
    moment (date) { 
    return moment(date).format('DD.MM.YYYY HH:mm:ss'); 
    } 
} 

и назвать его с

<td rowspan="2">{{difference.resolved_date ? moment(difference.resolved_date) : null }}</td> 

Вот обновленный JSBin: https://jsbin.com/zifugidogu/edit?html,js,console,output

+1

Отлично, работает как шарм. Большое спасибо! –

0

Вероятно, вы должны переместить определение фильтра в Vue «конструктор»

data: { 
    ... 
    filters: { 
     'moment', function (date) { 
      return moment(date).format('DD.MM.YYYY HH:mm:ss'); 
     } 
    } 
} 
+0

Я уже пробовал, без результата, по-прежнему то же самое. Вы можете проверить это здесь https://jsbin.com/melequjufi/edit?html,js,console,output –

+0

, по-видимому, вам нужно поставить это определение внутри объекта 'data' – mic4ael

Смежные вопросы