我正在使用 Prop 来更新子组件中的网站内容。这基本上是这样工作的:
<child-component :updatedArray="updatedArray" />
然后在子组件中:<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>
现在,当我更新 updatedArray
时,这段代码在任何情况下都应该可以工作。在我的父组件中。然后我在我的子组件中看到我的 {{updatedArray}}
更改正确,但我的 computedArray
未触发且不起作用。我能问你为什么会这样吗?
计算是否不适用于每个 Prop 更新?
我应该如何更正我的代码?
编辑:不重复
我没有改变 Prop ,我宁愿只根据它的值进行计算。
最佳答案
您的绑定(bind)使用了错误的名称。
如Vue Guide描述:
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
所以你需要转换 Camel 箱至烤肉串 .
喜欢
v-bind:updated-array
而不是 v-bind:updatedArray
.下面是一个使用 kebab-case 的工作演示。您可以将其更改为camelCase,然后您会发现不起作用。
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>
关于vue.js - vuejs - 计算不适用于 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49614574/