[英]Why Vue can't watch the data change?
i want the function:createComparation work when tableRowName change,but acturely when tableRowName change, it didnt works,vue follows;我希望 function:createComparation 在 tableRowName 更改时工作,但实际上当 tableRowName 更改时,它没有工作,vue 跟随; createComparation is another function which didnt define by vue but only by javascript createComparation 是另一个 function,它不是由 vue 定义的,而是由 javascript 定义的
const selectedRight =Vue.createApp({
data(){
return {
tableRow:0,
tableRowName:[],
stockName:[],
rectWidth:40,
rectHeight:5,
}
},
watch: {
tableRowName(newtable,oldtable){
console.log(1)
createComparation()
},
immediate:true,
stockName(){
changeTip()
},
},
methods:{
}
}).mount('#selectedRight')
I guess whatching array might be the issue.我猜 whatching 数组可能是问题所在。 You can try this:你可以试试这个:
computed: {
rowNames() {
return this.tableRowName;
// if the line above doesn't work:
return this.tableRowName.join();
}
},
watch: {
rowNames(newtable,oldtable){
createComparation()
},
in case of tableRowName contain objects then you have to use如果tableRowName包含对象,则必须使用
deep:true深:真
watch: {
tableRowName(newtable,oldtable){
console.log(1)
createComparation()
},
immediate:true,
deep: true,
stockName(){
changeTip()
},
},
but i think you are updating the array without reactive manner, Vue cannot detect the following changes to an array:但我认为你是在没有反应方式的情况下更新数组,Vue 无法检测到数组的以下更改:
When you directly set an item with the index, eg当您直接使用索引设置项目时,例如
vm.items[indexOfItem] = newValue vm.items[indexOfItem] = newValue
When you modify the length of the array, eg当您修改数组的长度时,例如
vm.items.length = newLength vm.items.length = newLength
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
vm.items[1] = 'x' // is NOT reactive
vm.items.length = 2 // is NOT reactive
I think this is what you're looking for.我想这就是你要找的。 You need to define the handler as an object for the property you're trying to watch and set immediate: true
.您需要将处理程序定义为 object 以用于您尝试监视的属性并设置immediate: true
。
Vue.config.productionTip = false Vue.config.devtools = false new Vue({ el: "#app", data() { return { tableRow: 0, tableRowName: [], stockName: [], rectWidth: 40, rectHeight: 5, } }, watch: { tableRowName: { handler(newtable) { console.log('Calling createComparation function'); console.info(newtable); }, immediate: true } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <button @click="tableRowName.push(Math.random())">Trigger change manually again</button> </div>
The watch method definition is wrong. watch 方法定义错误。 When you need to use immediate, you have to put you function body into handler property.当您需要立即使用时,您必须将 function 主体放入处理程序属性中。
For example,例如,
watch: {
tableRowName: {
handler: function() {
},
immediate: true
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.