Vue官方文档中的一句话说:
$ refs ...没有反应。
但是,我在模板中使用了这种引用,它们确实是反应性的,甚至在方法,计算的道具和观察者中也是如此(只要您在安装后访问它即可)。几个第三方Vue库(例如,该库)还提供使用/取决于ref的反应性的功能。
有人可以请您澄清一下裁判没有反应的正式文件是什么意思吗?
您会误解在Vue框架中响应是什么意思。当然,$refs在安装组件时,可以在设置完对象后访问对象的值,但这并不意味着该对象是反应性的。
When data is reactive, it means that changes to the value of that data will trigger a "reaction" from some part of the component that depends on that data's value, such as re-rendering the template, recalculating a computed variable, or triggering a watcher.
Read through the documentation on reactivity.
Here's an example:
Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
el: '#app',
mounted() {
console.log('$refs.foo in mounted', this.$refs.foo);
},
watch: {
'$refs.foo':{
immediate: true,
handler(value) {
console.log('$refs.foo watcher', value);
}
}
}
})Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div ref="foo"></div>
<div v-if="$refs.foo">
If $refs.foo was reactive, the template would update and you would see this message
</div>
</div>Run Code Online (Sandbox Code Playgroud)
In that example, you can see that the watcher for $refs.foo initially logs that the value of $refs.foo is undefined. This makes sense because the watcher has fired before the component has mounted, so the properties of the $refs object haven't been set yet. Then, in the mounted hook, we see that the value of $refs.foo has been set as expected.
如果$refs是反应式的,那么我们将看到模板更新,因为该v-if="$refs.foo"指令的计算结果为true。我们还将看到观察者$refs.foo在设置了值之后再次触发,记录了的新值$refs.foo。但是,由于$refs不是被动的,所以这两种情况均不会发生。
| 归档时间: |
|
| 查看次数: |
902 次 |
| 最近记录: |