[英]Not calling watch even after the prop change in vue.js
我不能使用immediate:true
,除了 immediate true 是我能做的另一件事嗎? 為什么即使在 prop 中的數據更改后 watch 也不調用? 只有在應用程序加載時它才第一次調用。
export default {
name: "Tabs",
data () {
return {
init: false,
currentTab: "tab-0",
tab: null,
}
},
props: {
config: {
type: Object,
default: undefined
},
dynamicSelection: 0
},
}
watch: {
config: {
handler: function (val) { //need to do something }
}
}
我懷疑您正在經歷 vue 的“反應性警告”。 這可能取決於您如何改變您作為配置值傳遞的 object。
例如:
<template>
<div id="app">
<HelloWorld :config="config"/>
<button @click="clicked1">This will update</button>
<button @click="clicked2">This will not update</button>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld
},
data(){
return {
config: { x: 1 }
}
},
methods: {
clicked1(){
this.config = { x: this.config.x + 1 }
},
clicked2(){
this.config.x++
}
}
};
</script>
如果 HelloWorld 正在監視配置值,它只會在整個 object 重置時更新。
嘗試為您的觀察者添加deep: true
。
watch: {
config: {
handler(){
this.watchCounter++
},
deep: true
}
}
我添加了帶有一些示例代碼的代碼框鏈接: https://codesandbox.io/s/charming-cohen-jgn3d單擊按鈕並注意單擊“這不會更新”時它不會更新。 在 HellowWorld 組件中取消注釋deep: true
以查看它如何解決問題。
在官方文檔中閱讀有關反應性警告的更多信息。 https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.