我正在尝试获取canvas元素,它位于组件的模板中,为vuejs1找到了很好的文档,但对于vuejs2没有找到,其中"ref“是获取元素的唯一方法。虽然我正在获取对象,但是当我试图访问变量时,它是未定义的。
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')我要去拿icanvas元素。

发布于 2016-11-30 09:21:23
created是在处理模板之前触发的。
您可以在这里找到更多详细信息:https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram
您应该能够访问mounted事件上的mounted
mounted: function() {
console.log(this.$refs.icanvas);
},发布于 2018-06-28 10:46:25
您可以使用$nextTick()函数,$nextTick()内部的代码将在DOM更新后运行。
this.$nextTick(function () {
console.log(this.$refs.ANY_COMPONENT_REF)
})发布于 2018-07-12 08:41:06
我也遇到了同样的问题,在我的例子中,我通过访问使用nextTick更改v-if的方法中的ref来解决它。
methods: {
open() {
this.show = true; //v-if condition
this.$nextTick(function() {
this.titleWidth = this.$refs.titleBg.clientWidth - 30;
});
}https://stackoverflow.com/questions/40884194
复制相似问题