2016-11-23 80 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