如何在Vue中动态创建的组件上获取更新的$ ref? [英] How to get updated $refs on dynamically created component in Vue?

查看:194
本文介绍了如何在Vue中动态创建的组件上获取更新的$ ref?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件数量取决于数组数量,因此当我向数组添加新项目时,它应该创建新组件.

My amount of components depends on array quantity, so when i add new item to array, it should create new component.

在创建新组件时,我想获得有关它的参考,这就是我产生误解的地方.当我尝试获取它时,最后添加的组件是 undefined .

When new component is created i want to get reference on it, and that's where i have a misunderstanding. Last added component is undefined when i try to get it.

但是,如果我试图在一段时间后获得参考,它会起作用.我想这是因为异步,但是我不确定.

But, if i trying to get reference on it after some time, it work. I guess it's because of asynchronous, but i'm not sure.

为什么会发生这种情况,以及是否有避免使用 setTimeout 的方法?

Why this is happening and if there a way to avoid using setTimeout?

<div id="app">
    <button @click="addNewComp">add new component</button>
    <new-comp
        v-for="compId in arr"
        :ref="`components`"
        :index="compId"
        ></new-comp>
    </div>
  <script type="text/x-template " id="compTemplate">
    <h1> I am a component {{index}}</h1>
</script>


Vue.component("newComp",{
  template:"#compTemplate",
  props:['index']
})
new Vue({
  el:"#app",
  data:{
    arr:[1,2,3,4]
  },
  methods:{
    addNewComp:function(){
      let arr = this.arr;
      let components = this.$refs.components;
      arr.push(arr.length+1);
      console.log("sync",components.length);
      console.log("sync",components[components.length-1])
      setTimeout(() => {
        console.log("async",components.length);
        console.log("async",components[components.length-1])
      }, 1);
    }
  }
})

codepen链接

推荐答案

ref s和 $ refs 都没有反应.

如果要获取更新的值,则应等待下一个渲染周期更新DOM.

If you want to pick up the updated value, you should wait until the next render cycle updates the DOM.

您应该使用 Vue.nextTick而不是 setTimeout () :

new Vue({
  el:"#app",
  data:{
    arr:[1,2,3,4]
  },
  methods:{
    addNewComp:function(){
      let arr = this.arr;
      let components = this.$refs.components;
      arr.push(arr.length+1);
      console.log("sync",components.length);
      console.log("sync",components[components.length-1])
      Vue.nextTick(() => {                                         // changed here
        console.log("async",components.length);
        console.log("async",components[components.length-1])
      });                                                          // changed here
    }
  }
})

这不是"hack",这是正确的方法.来自官方API文档:

And this is not a "hack", this is the proper way of doing it. From the official API docs:

Vue.nextTick([回调,上下文])

  • 参数:

  • {Function} [回调]
  • {Object} [上下文]

用法:

推迟下一个DOM更新周期后执行的回调.更改一些数据以等待DOM后立即使用它更新.

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you've changed some data to wait for the DOM update.

// modify data
vm.msg = 'Hello'
// DOM not updated yet
Vue.nextTick(function () {
  // DOM updated
})

// usage as a promise (2.1.0+, see note below)
Vue.nextTick()
  .then(function () {
    // DOM updated
  })

这篇关于如何在Vue中动态创建的组件上获取更新的$ ref?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆