Vuejs无法从组件访问引用

Cod*_*ree 26 vue.js vue-component vuejs2

我正在尝试获取组件模板内的canvas元素,为vuejs1找到了很棒的文档但不是vuejs2,其中"ref"是获取元素的唯一方法.我正在获取对象,但是当我尝试访问变量时,它是未定义的.

我的HTML

<div id="app>
  <template id="image-capture">
    <div class="row" >
      <canvas ref="icanvas" ></canvas>
    </div>
  </template>
</div>
Run Code Online (Sandbox Code Playgroud)

我的js

const ic = {
  template: '#image-capture' ,

  created () {
    console.log(this.$refs); //this returns object
    console.log(this.$refs.icanvas); // but this is undefined
  }


}

const routes = [
  { path: '/ic', component:   ic},
]

const router = new VueRouter({
  routes 
})

 new Vue({
  router,
   }).$mount('#app')
Run Code Online (Sandbox Code Playgroud)

我需要获得icanvas元素.

这是控制台日志

Mih*_*lcu 26

created处理模板之前被激发.
您可以在此处找到更多详细信息:https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

您应该能够访问该mounted事件的$ refs

mounted: function() {
    console.log(this.$refs.icanvas);
},
Run Code Online (Sandbox Code Playgroud)

  • 那就对了.不幸的是,如果你的`ref`是'v-for`元素,它仍然是一个问题.当`mount`hook被触发时,DOM无法访问这个`ref`.对此有何建议?谢谢 ! (19认同)

Kis*_*iya 9

你可以使用$ nextTick()函数,$ nextTick()里面的代码将在DOM更新后运行.

this.$nextTick(function () {

    console.log(this.$refs.ANY_COMPONENT_REF)

})
Run Code Online (Sandbox Code Playgroud)

  • 它也不适合我 (3认同)
  • 不,这与我在案例中描述的OP不能解决同样的问题。我在组件中有一些引用,在安装时我试图为这些引用添加动画,但是它们以“未定义”的形式出现。我的组件中没有v-for或v-if或任何其他阻止程序,这可能会引起问题。 (2认同)

小智 9

我遇到了完全相同的问题,在我的情况下,我通过访问使用 nextTick 更改 v-if 的方法中的 ref 来解决它。

methods: {
open() {
  this.show = true; //v-if condition
    this.$nextTick(function() {
      this.titleWidth = this.$refs.titleBg.clientWidth - 30;
    });
}
Run Code Online (Sandbox Code Playgroud)


小智 5

@Dan Levin 的答案有效。

methods: {
fecthData() {
    this.data ={ ... }; // assume the fetched data have changed DOM here.

    this.$nextTick(() => {
      console.log(this.$refs); // returns obj
      console.log(this.$refs.target); // returns el
    });
}
Run Code Online (Sandbox Code Playgroud)

这也适用于 v-for。