虽然Vue Composition API RFC Reference site的watch
模块具有许多高级使用场景,但没有如何观看道具道具的示例?
在Vue Composition API RFC's main page或vuejs/composition-api in Github中都没有提及。
我已经创建了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>
编辑:尽管我的问题和代码示例最初是使用JavaScript编写的,但实际上我正在使用TypeScript。托尼·汤姆(Tony Tom)的第一个答案虽然有效,但会导致类型错误。这由MichalLevý的答案解决。因此,之后我用typescript
标记了这个问题。
EDIT2 :这是我针对此自定义选择组件的无功布线的抛光但准系统的版本,位于<b-form-select>
的bootstrap-vue
上方(否则不可知,实现,但此基础组件会根据是通过编程还是通过用户交互来进行更改,都发出@input和@change事件。。
<template>
<b-form-select
v-model="selected"
:options="{}"
@input="handleSelection('input', $event)"
@change="handleSelection('change', $event)"
/>
</template>
<script lang="ts">
import {
createComponent, SetupContext, Ref, ref, watch, computed,
} from '@vue/composition-api';
interface Props {
value?: string | number | boolean;
}
export default createComponent({
name: 'CustomSelect',
props: {
value: {
type: [String, Number, Boolean],
required: false, // Accepts null and undefined as well
},
},
setup(props: Props, context: SetupContext) {
// Create a Ref from prop, as two-way binding is allowed only with sync -modifier,
// with passing prop in parent and explicitly emitting update event on child:
// Ref: https://vuejs.org/v2/guide/components-custom-events.html#sync-Modifier
// Ref: https://medium.com/@jithilmt/vue-js-2-two-way-data-binding-in-parent-and-child-components-1cd271c501ba
const selected: Ref<Props['value']> = ref(props.value);
const handleSelection = function emitUpdate(type: 'input' | 'change', value: Props['value']) {
// For sync -modifier where 'value' is the prop name
context.emit('update:value', value);
// For @input and/or @change event propagation
// @input emitted by the select component when value changed <programmatically>
// @change AND @input both emitted on <user interaction>
context.emit(type, value);
};
// Watch prop value change and assign to value 'selected' Ref
watch(() => props.value, (newValue: Props['value']) => {
selected.value = newValue;
});
return {
selected,
handleSelection,
};
},
});
</script>
答案 0 :(得分:3)
我只是想在上面的答案中添加更多详细信息。正如Michal所提到的,props
是一个对象,整体上是反应性的。但是,props对象中的每个键都不是独立的。
与watch
值相比,我们需要调整reactive
对象中的值的ref
签名
// watching value of a reactive object (watching a getter)
watch(() => props.selected, (selection, prevSelection) => {
/* ... */
})
// directly watching a ref
const selected = ref(props.selected)
watch(selected, (selection, prevSelection) => {
/* ... */
})
仅提供一些更多信息,即使它不是问题中提到的情况: 如果我们要监视多个属性,则可以传递一个数组而不是单个引用
// Watching Multiple Sources
watch([ref1, ref2, ...], ([refVal1, refVal2, ...],[prevRef1, prevRef2, ...]) => {
/* ... */
})
答案 1 :(得分:2)
如果您查看watch
,并键入here(最后一个项目符号),则可以清楚地看到watch
的第一个参数可以是数组,函数或Ref<T>
props
函数的 setup
是反应性对象(可能由reactive()
制造),它的属性是吸气剂。因此,您要做的就是将getter的值作为watch
的第一个参数传递-在这种情况下为字符串“ initial”。由于Vue 2 $watch
API是在后台使用的,因此您实际上在尝试在组件实例上监视名称为“ initial”的不存在的属性。您的回调仅被调用一次,不再调用。之所以调用它至少一次是因为新的watch
API的行为类似于具有$watch
选项的当前immediate
。
因此,偶然地,您做的事情与托尼·汤姆(Tony Tom)所建议的相同,但价值错误。在两种情况下,如果您使用的是TypeScript,那都是无效的代码
您可以改为:
watch(() => props.selected, (first, second) => {
console.log(
"Watch props.selected function called with args:",
first,
second
);
});
这是watch API docs的第二个例子
其他方法是使用toRefs
转换props对象,使其属性为Ref<T>
类型,您可以将其作为watch
的第一个参数传递
答案 2 :(得分:1)
按如下所示更改您的观看方法。
watch("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
});
答案 3 :(得分:1)
这没有解决如何“监视”属性的问题。但是,如果您想知道如何使道具通过Vue的Composition API做出响应,请继续阅读。在大多数情况下,您不必编写大量代码来“监视”事物(除非您在更改后会产生副作用)。
秘密在于:组件props
是被动的。一旦您访问特定的道具,它就不会反应。划分或访问对象的一部分的过程称为“解构”。在新的Composition API中,您需要经常思考这一点-这是决定使用reactive()
与ref()
的关键部分。
因此,我建议(下面的代码)是您要保留所需的属性,并将其设置为ref
:
export default defineComponent({
name: 'MyAwesomestComponent',
props: {
title: {
type: String,
required: true,
},
todos: {
type: Array as PropType<Todo[]>,
default: () => [],
},
...
},
setup(props){ // this is important--pass the root props object in!!!
...
// Now I need a reactive reference to my "todos" array...
var todoRef = toRefs(props).todos
...
// I can pass todoRef anywhere, with reactivity intact--changes from parents will flow automatically.
// To access the "raw" value again:
todoRef.value
// Soon we'll have "unref" or "toRaw" or some official way to unwrap a ref object
// But for now you can just access the magical ".value" attribute
}
}
我当然希望Vue向导能够弄清楚如何使它更容易...但是据我所知,这是我们必须使用Composition API编写的代码类型。
这里是link to the official documentation,他们在那里直接警告您不要破坏道具。
答案 4 :(得分:0)
您可以使用路径到达给定的属性:
watch("props.value", (newValue: Props['value']) => {
selected.value = newValue;
});