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)
你可以使用$ nextTick()函数,$ nextTick()里面的代码将在DOM更新后运行.
this.$nextTick(function () {
console.log(this.$refs.ANY_COMPONENT_REF)
})
Run Code Online (Sandbox Code Playgroud)
小智 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。
| 归档时间: |
|
| 查看次数: |
36645 次 |
| 最近记录: |