Jaroslav KlimĨík Jaroslav KlimĨík - 17 days ago 13
Javascript Question

Vue.js - update parent data with filter

I'm beginner with Vue.js and I would like to update parent data after ajax in component is finished. Problem is when I use filter

moment
, without filter is everything fine but I need this filter. First rendering is without problem because column
resolved_date
is empty. But after ajax is called and data are emitted from component to parent, I want to update parent data (
resolved_date
) but I will get error:

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)


So far I have:

Edit: here is this JS Bin example with same error.

<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>


How can I update data with filter without getting any error?

Answer

Filters don't work in this case, because you want to use them in a ternary expression. (Currently, you'll make a bitwise | comparison with this.moment, which isn't set. That's why you get the Warning.)

You can simply use a method instead:

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

and call it with

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

Here is the updated JSBin: https://jsbin.com/zifugidogu/edit?html,js,console,output