我正在使用道具更新子组件中的站点内容。这基本上是这样工作的:
<child-component :updatedArray="updatedArray" />
Run Code Online (Sandbox Code Playgroud)
然后在子组件中:
<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>
Run Code Online (Sandbox Code Playgroud)
现在,当我updatedArray在我的父组件中更新时,这段代码应该可以在任何情况下工作。然后我在我的子组件中看到我{{updatedArray}}的正在正确更改,但我computedArray的未触发并且不起作用。
我能问你为什么会这样吗?计算是否不适用于每个道具更新?
我应该如何更正我的代码?
编辑:不重复我没有改变道具,我只是根据它的值进行计算。
您的绑定使用了错误的名称。
正如Vue 指南所描述的:
HTML 属性名称不区分大小写,因此浏览器会将任何大写字符解释为小写。这意味着当你使用 DOM 模板时,camelCased 道具名称需要使用它们的 kebab-cased(连字符分隔)等价物
所以你需要将camelCase转换为kebab-case。
喜欢v-bind:updated-array而不是v-bind:updatedArray.
下面是一个使用 kebab-case 的工作演示。您可以将其更改为驼峰大小写,然后您会发现不起作用。
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'
}
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18409 次 |
| 最近记录: |