问题
I'm using props to update my site content in child component. This is basically working like this:
<child-component>
:updatedArray="updatedArray"
</child-component>
then in the child component:
<template>
{{updatedArray}}
<div>{{computedArray}}</div>
</template>
<script>
props: ['updatedArray'],
...
computed: {
computedArray() {
if(this.updatedArray.item == "item one") {return "item one"}
else {return "other item"}
}
}
</script>
Now this code should work in any case when I update updatedArray
in my parent component. Then I see in my child component that my {{updatedArray}}
is changing correctly, but my computedArray
is not triggered and does not work.
Can I ask you why is this happening? Does computed do not work with every props update?
How should I correct my code?
edit: not duplicate I'm not mutating the prop, I rather only do a computed based on its value.
回答1:
Your bind uses wrong name.
As Vue Guide describes:
HTML attribute names are case-insensitive, so browsers will interpret any uppercase characters as lowercase. That means when you’re using in-DOM templates, camelCased prop names need to use their kebab-cased (hyphen-delimited) equivalents
So you need to convert camelCase to kebab-case.
like v-bind:updated-array
instead of v-bind:updatedArray
.
Below is one working demo using kebab-case. You can change it to camelCase, then you will find not working.
Vue.component('child', {
template: '<div><span style="background-color:green">{{ updatedArray }}</span><div style="background-color:red">{{computedArray}}</div></div>',
props: ['updatedArray'],
computed: {
computedArray() {
if(this.updatedArray.item.length > 0) {return this.updatedArray}
else {return "other item"}
}
}
})
new Vue({
el: '#app',
data() {
return {testArray: {
'item': 'test',
'prop1': 'a'
}}
},
methods:{
resetArray: function() {
this.testArray['item'] += this.testArray['prop1'] + 'b'
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<button v-on:click="resetArray()">Click me</button>
<child v-bind:updated-array="testArray"></child>
</div>
来源:https://stackoverflow.com/questions/49614574/vuejs-computed-is-not-working-with-props