Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

vue.js - Vuejs can't access refs from component

I am trying to get the canvas element which is inside a template of a component, found great documentations for vuejs1 but not for vuejs2 where "ref" is the only way to get the element. I am getting the object though, but when I try to access the variable it is undefined.

HTML

<div id="app>
  <template id="image-capture">
    <div class="row" >
      <canvas ref="icanvas" ></canvas>
    </div>
  </template>
</div>

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')

I need to get the icanvas element.

here is console log

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The created is fired before the template is processed.
You can find more details here: https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

You should be able to access the $refs on the mounted event

mounted: function() {
    console.log(this.$refs.icanvas);
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...