为什么观看仅触发一次?如下代码所示,当单击“同步”按钮时,id和文本同时更改,但是只有id()监视被触发,需要再次单击“ sync”按钮以触发text()监视,为什么?
Vue.component('test-bar', {
props: ['id', 'text'],
template: `
<div>
<div>child: {{id}} {{text}}</div>
<button @click="on_click">sync</button>
</div>
`,
watch: {
id() {
this.$emit('update:id', this.id)
// this.$emit('update:text', this.text) // !!! notice here. only when i added this line will trigger text() watch
},
text() {
this.$emit('update:text', this.text)
}
},
methods: {
on_click() {
this.id = 1
this.text = 'child text'
}
}
})
new Vue({
el: "#app",
data: {
id: 0,
text: 'parent text',
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<test-bar :id.sync='id' :text.sync='text'></test-bar>
<div>parent: {{id}} {{text}}</div>
</div>
答案 0 :(得分:0)
您不应该更新[
{
"product_id": "1",
"delivery_product_qty": 4
"sales_product_qty": "3"
},
{
"product_id": "2",
"delivery_product_qty": 1
"sales_product_qty": "3"
}
]
。尝试更新道具时,Vue将引发错误,并且流程将中断。因此,在此行props
之后,将引发异常,并且下一行将不执行。正确的方法是将computed property与getter和setter一起使用。
类似的东西:
this.id = 1
这是一个jsfiddle工作example
一种更简单的方法是仅发出事件而不关注更改
Vue.component('test-bar', {
props: ['id', 'text'],
template: `
<div>
<div>child: {{childId}} {{childText}}</div>
<button @click="on_click">sync</button>
</div>
`,
computed: {
childId: {
get () {
return this.id
},
set (value) {
this.$emit('update:id', value)
}
},
childText: {
get () {
return this.text
},
set (value) {
this.$emit('update:text', value)
}
}
},
methods: {
on_click() {
this.childId = 1
this.childText = 'child text'
}
}
})
JSfiddle example