2016-11-23 82 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) 

到目前为止,我有:

编辑:这里是这个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