While Vue Composition API RFC Reference site has many advanced use scenarios with the watch
module, there is no examples on how to watch component props ?
(尽管Vue Composition API RFC参考站点在watch
模块中具有许多高级使用场景,但没有有关如何监视组件prop的示例?)
Neither is it mentioned in Vue Composition API RFC's main page or vuejs/composition-api in Github .
(在Vue Composition API RFC的主页或Github中的vuejs / composition-api中都未提及。)
I've created a Codesandbox to elaborate this issue.
(我创建了一个Codesandbox来详细说明此问题。)
<template>
<div id="app">
<img width="25%" src="./assets/logo.png">
<br>
<p>Prop watch demo with select input using v-model:</p>
<PropWatchDemo :selected="testValue"/>
</div>
</template>
<script>
import { createComponent, onMounted, ref } from "@vue/composition-api";
import PropWatchDemo from "./components/PropWatchDemo.vue";
export default createComponent({
name: "App",
components: {
PropWatchDemo
},
setup: (props, context) => {
const testValue = ref("initial");
onMounted(() => {
setTimeout(() => {
console.log("Changing input prop value after 3s delay");
testValue.value = "changed";
// This value change does not trigger watchers?
}, 3000);
});
return {
testValue
};
}
});
</script>
<template>
<select v-model="selected">
<option value="null">null value</option>
<option value>Empty value</option>
</select>
</template>
<script>
import { createComponent, watch } from "@vue/composition-api";
export default createComponent({
name: "MyInput",
props: {
selected: {
type: [String, Number],
required: true
}
},
setup(props) {
console.log("Setup props:", props);
watch((first, second) => {
console.log("Watch function called with args:", first, second);
// First arg function registerCleanup, second is undefined
});
// watch(props, (first, second) => {
// console.log("Watch props function called with args:", first, second);
// // Logs error:
// // Failed watching path: "[object Object]" Watcher only accepts simple
// // dot-delimited paths. For full control, use a function instead.
// })
watch(props.selected, (first, second) => {
console.log(
"Watch props.selected function called with args:",
first,
second
);
// Both props are undefined so its just a bare callback func to be run
});
return {};
}
});
</script>
EDIT : Although my question and code example was initially with JavaScript, I'm actually using TypeScript.
(编辑 :尽管我的问题和代码示例最初是使用JavaScript的,但实际上我正在使用TypeScript。)
Tony Tom's first answer although working, lead to a type error.(托尼·汤姆(Tony Tom)的第一个答案虽然有效,但却导致类型错误。)
Which was solved by Michal Levy's answer.(这由MichalLevy的答案解决。)
So I've tagged this question with typescript
afterwards.(所以我后来用typescript
标记了这个问题。)
ask by ux.engineer translate from so