无法访问组件挂载回调中

无法访问组件挂载回调中

本文介绍了无法访问组件挂载回调中 v-if 显示的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<div><transition name="fade" mode="out-in"><div class="ui active inline loader" v-if="loading" key="loading"></div><div v-else key="已加载"><span class="foo" ref="foo">我要的内容就在这里</span>

</模板><脚本>导出默认{数据() {返回 {加载:假}},安装(){setTimeout(() => {//模拟异步操作this.loaded = trueconsole.log($(this.$refs.foo).length, $(this.$el.find('.foo')).length)}, 2000)},}

无论我使用 this.$refs 还是 this.$el,我都只能访问加载器 div (<div class="ui active inline loader"/>).

我应该如何访问安装组件时不存在的元素?我是否必须将 v-if 更改为 v-show?

解决方案

Vue 渲染到 DOM 异步.因此,即使您将加载的属性设置为 trueref 也不会存在,直到 Vue 周期的下一个滴答声.

要处理该问题,请使用 $nextTick方法.

console.clear()新的 Vue({el: "#app",数据:{加载:真实},安装(){setTimeout(()=>{this.loading = falsethis.$nextTick(() => console.log(this.$refs.done))}, 1000)}})
<script src="https://unpkg.com/[email protected]"></script><div id="应用程序"><div v-if="加载">加载</div><div ref="done" v-else>完成</div>

另外,在这个问题中,v-if 表达式是 loading,它总是未定义的,因为数据属性被称为 loaded.

<template>
<div>
    <transition name="fade" mode="out-in">

      <div class="ui active inline loader" v-if="loading" key="loading"></div>
      <div v-else key="loaded">
          <span class="foo" ref="foo">the content I'm after is here</span>
      </div>

    </transition>
</div>
</template>

<script>
    export default {
        data() {
            return {
                loaded: false
            }
        },
        mounted() {
            setTimeout(() => {  // simulate async operation
                this.loaded = true
                console.log($(this.$refs.foo).length, $(this.$el.find('.foo')).length)
            }, 2000)
        },
    }
</script>

Regardless if I use this.$refs or this.$el, I'm only able to access the loader div (<div class="ui active inline loader"/>).

How am I supposed to access an element which doesn't exist when the component is mounted? Do I have to change v-if to v-show?

解决方案

Vue renders to the DOM asynchronously. So, even though you are setting your loaded property to true, the ref will not exist until the next tick in Vue's cycle.

To handle that, use the $nextTick method.

console.clear()

new Vue({
  el: "#app",
  data:{
    loading: true
  },
  mounted(){
    setTimeout(()=> {
      this.loading = false
      this.$nextTick(() => console.log(this.$refs.done))
    }, 1000)
  }
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
  <div v-if="loading">Loading</div>
  <div ref="done" v-else>Done</div>
</div>

Additionally, in the question, the v-if expression is loading which will always be undefined because the data property is called loaded.

这篇关于无法访问组件挂载回调中 v-if 显示的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 14:01