如果用户登录,我有一个使用 v-if="isLogged"
有条件渲染的元素:
<div
v-if="isLogged"
class="chatBlock"
ref="chat"
></div>
我正在尝试在 mounted ()
函数中获取 chat
引用的滚动高度 - this.$refs.logged.scrollHeight
,但这是不可能的,因为如果用户没有登录,那么这个 div
不会在安装阶段渲染,所以即使用户登录 - 它也不会工作,因为安装阶段已经过去了。
是否可以使用 watch
方法跟踪 DOM 中的元素外观?
更新
添加了观察者,正如 Steven 在下面的 mounted ()
中建议的那样:
this.$store.watch(
(state) => {
return this.$store.getters.isLogged
},
(newValue, oldValue) => {
if (newValue) {
this.chatHeight = this.$refs.chat.scrollHeight
}
}
)
最佳答案
接受的答案对我不起作用。 watch 不保证元素已经渲染。
为了确保该元素可用,我必须使用 $nextTick
if (newValue) {
this.$nextTick(function () {
this.chatHeight = this.$refs.chat.scrollHeight
})
}
这将导致代码在下一个 DOM 更新周期之后执行。
关于javascript - 如何访问在 v-if 中条件渲染的 ref 元素 - Vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53578419/