Vuejs Using Computed Property For Array Elements
I've got basic template that is outputing text from wysiwyg editor via two-ways data binding as below:
new Vue({
el: '#app',
data: {
arr: [1, 2, 3]
},
computed: {
carr() {
console.log("Computing the whole array");
return this.arr.map(x => 'hi ' + x);
}
},
components: {
addHi: {
props: ['value'],
template: '<div>{{a}}</div>',
computed: {
a() {
console.log("Computing for", this.value);
return 'hi ' + this.value;
}
}
}
},
created() {
setTimeout(() => {
console.log("** Changing a value");
this.arr.splice(2, 1, 'X');
}, 1500);
}
});
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<div v-for="a in carr">{{a}}</div>
<add-hi v-for="a in arr" :value="a" :key="a"></add-hi>
</div>
If you need your computed to be writable, you won't be able to edit individual items, so you're really forced to make a component. It is pretty straightforward: just move the HTML into the template of the component, move the computed into the component (adjusting it to work on the prop value
), and then – because it is operating on a prop – change the set
function to use $emit
rather than changing its value directly.
debouncedQuillEditor: {
props: ['value', 'options'],
template: '<quill-editor v-model="debouncedValue" :options="options"></quill-editor>',
computed: {
debouncedValue: {
get() {
return this.value;
},
set: _.debounce(function(newValue) {
this.$emit('input', newValue);
}, 100)
}
}
},
I made a fiddle to demonstrate. I made a second component to handle the output HTML, although it could have been included in the first component.
Post a Comment for "Vuejs Using Computed Property For Array Elements"