gpt4 book ai didi

javascript - Vue.js : How to fire a watcher function when a component initializes

转载 作者:搜寻专家 更新时间:2023-11-01 05:09:27 24 4
gpt4 key购买 nike

有时我需要调用一些函数来响应数据属性的变化。但是,我还需要该函数来触发数据属性的初始值。

观察者不会在组件初始化时触发,因为技术上被观察的属性还没有改变。所以,我最终将函数放在 methods 对象中,然后在 watcher 和 mounted Hook 中调用该方法。

这是一个例子:

new Vue({ 
el: '#app',
data() {
return {
selectedIndex: 0,
}
},
methods: {
focusSelected() {
this.$refs.input[this.selectedIndex].focus();
}
},
watch: {
selectedIndex() {
this.focusSelected();
}
},
mounted() {
this.focusSelected();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<div v-for="i in 4">
<input ref="input"/>
<button @click="selectedIndex = (i - 1)">Select</button>
</div>
</div>

有没有办法让我在组件初始化时触发观察者?

最佳答案

Watchers in Vue可以选择提供立即值:

Passing in immediate: true in the option will trigger the callback immediately with the current value of the expression

在这种情况下,您可以在 mounted Hook 中设置观察者:

new Vue({ 
el: '#app',
data() {
return {
selectedIndex: 0,
}
},
mounted() {
this.$watch('selectedIndex', (i) => {
this.$refs.input[i].focus();
}, { immediate: true });
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<div v-for="i in 4">
<input ref="input"/>
<button @click="selectedIndex = (i - 1)">Select</button>
</div>
</div>


您还可以在 watch 对象中为观察者指定 immediate 选项,如下所示:

watch: {
foo: {
immediate: true,
handler(value) {
this.bar = value;
}
}
}

关于javascript - Vue.js : How to fire a watcher function when a component initializes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45354027/

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