Vue.js: How to fire a watcher function when a component initializes(Vue.js:如何在组件初始化时触发观察器函数)
问题描述
Sometimes I need to call some function in response to a change in a data property. But, I also need that function to fire for the initial value of the data property.
The watcher does not fire when the component initializes since the property being watched technically hasn't changed yet. So, I end up putting the function in the methods
object, and then calling that method in the watcher and the mounted
hook.
Here's an example:
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="aHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS9hamF4L2xpYnMvdnVlLzIuNC4yL3Z1ZS5taW4uanM="></script>
<div id="app">
<div v-for="i in 4">
<input ref="input"/>
<button @click="selectedIndex = (i - 1)">Select</button>
</div>
</div>
Is there a way for me to be able to have the watcher fire when the component initializes?
Watchers in Vue have an option to provide an immediate
value:
Passing in
immediate: true
in the option will trigger the callback immediately with the current value of the expression
In this case, you could set a watcher in the mounted
hook:
new Vue({
el: '#app',
data() {
return {
selectedIndex: 0,
}
},
mounted() {
this.$watch('selectedIndex', (i) => {
this.$refs.input[i].focus();
}, { immediate: true });
}
})
<script src="aHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS9hamF4L2xpYnMvdnVlLzIuNC4yL3Z1ZS5taW4uanM="></script>
<div id="app">
<div v-for="i in 4">
<input ref="input"/>
<button @click="selectedIndex = (i - 1)">Select</button>
</div>
</div>
You could also specify the immediate
option for a watcher in the watch
object like so:
watch: {
foo: {
immediate: true,
handler(value) {
this.bar = value;
}
}
}
这篇关于Vue.js:如何在组件初始化时触发观察器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Vue.js:如何在组件初始化时触发观察器函数
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01