gpt4 book ai didi

vue.js - Vue Trigger watch on mounted

转载 作者:搜寻专家 更新时间:2023-10-30 22:09:14 25 4
gpt4 key购买 nike

我下面有一个 vue 组件,我想在它安装时触发它。我该怎么做?

Vue.component('check-mark', {
name: 'check-mark',
template: `<input :value="value"/>`,
props: {
value: {
type: String,
required: true,
},
},
mounted: async function () {
//trigger this.value watch() here
},
watch: {
value: function (value) {
if (value == 'Y') {
this.class = 'checked';
} else {
this.class = 'unchecked';
}
},
},
});

最佳答案

从 Vue 2.0 开始,现在可以使用 immediate: true 在 watcher 本身中执行此操作。
对于在生命周期中何时运行观察者有一个小警告,请参阅编辑。

Before using this, ensure you really need a watcher rather than a computed property.

There are many advantages to computed properties and more often than not they are the better solution.

This functionality should only be used if computed properties are insufficient.

In the specific case of the original question, a computed property for class would definitely be better, but posted this just in case other people stumble across this post with a case where a computed property won't do (as I did).

Watchers可以是一个对象,而不仅仅是一个函数,并采用 immediate 属性,告诉 vue 在创建时运行观察器(不同于挂载)。

然后运行的函数位于 handler 属性中。

因此,在您的示例中,您的观察者可能是:

watch: {
value: {
handler: function(value) {
if (value == 'Y') {
this.class = 'checked';
} else {
this.class = 'unchecked';
}
},
immediate: true
},
}

编辑

评论中指出,immediate 选项会在组件创建 时触发观察器,而不是 < strong>安装。在简单的情况下,这些可以看作是等价的。
如果您真的特别想要观察者的 mounted 功能时运行,您可以简单地让您正在观察的字段成为一些虚拟值,比如 nullundefined,然后在 mounted() 钩子(Hook)中实际初始化它。上面的例子会变成:

data() {
return {
value: undefined
}
},
mounted() {
// Set value to actual initial value,
// which will trigger the watcher
this.value = 'Y';
},
watch: {
value(value) {
if (value == 'Y') {
this.class = 'checked';
} else {
this.class = 'unchecked';
}
}
}

关于vue.js - Vue Trigger watch on mounted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45223000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com