VUE 中 ref 和 refs
1、获取元素节点如下面代码所示:实际就相当于document.getElementById(‘the_right’)<!-- 此代码为VUE代码 --><template><div class="power"><div id="the_left"><Aside></Aside></div><div id="t
·
1、获取元素节点
如下面代码所示:实际就相当于 document.getElementById(‘the_right’)
<!-- 此代码为VUE代码 -->
<template>
<div class="power">
<div id="the_left">
<Aside></Aside>
</div>
<div id="the_center" @mousedown="get_width($event)"></div>
<div id="the_right" ref = 'test_id'>
<TableData :table_data = 'tableData'></TableData>
</div>
</div>
</template>
<script>
import Aside from './aside/aside.vue'
import TableData from './content/table_data.vue'
export default{
name:'Power',
components:{
Aside,
TableData
},
mounted() {
console.log(this.$refs.test_id)
//输出结果: <div data-v-a2f0dfca="" id="the_right">...</div>
}
}
</script>
2、访问子组件属性或方法
power.vue
<!-- 此代码为VUE代码 -->
<template>
<div class="power">
<div id="the_left">
<Aside></Aside>
</div>
<div id="the_center" @mousedown="get_width($event)"></div>
<div id="the_right" ref = 'test_id'>
<TableData :table_data = 'tableData'></TableData>
</div>
</div>
</template>
<script>
import Aside from './aside/aside.vue'
import TableData from './content/table_data.vue'
export default{
name:'Power',
components:{
Aside,
TableData
},
mounted() {
console.log(this.$refs.test_id.test_data())
//输出结果: aaa
console.log(this.$refs.test_id.isActive)
//输出结果: true
}
}
</script>
table_data.vue
<template>
<div class="table_content">
<el-button type="primary" class="el_bt" @click = 'set_data()'>立即创建</el-button>
<el-button class="el_bt" @click = 'show_data()'>取消</el-button>
</div>
</template>
<script>
export default{
props:['table_data'],
data(){
return{
isActive:true,
}
},
methods:{
test_data(){
console.log('aaa')
}
}
}
</script>
今天在父组件中使用ref调用子组件的方法 发现了一个错
TypeError: Cannot read properties of undefined (reading ‘getRecord’)
#解决方案
handleClick(id, type) {
this.partiCularsVisible = true;
this.$nextTick(()=>{
this.$refs.getCarRecord.getRecord();//将此调用包含在 this.$nextTick(()=>{})中即可
})
}
//原理:在使用this.$refs.getCarRecord.getRecord()时,会调用子组件,但是此时子组件还未渲染到父组件的DOM中,所以无法获取
//因此使用 VUE的this.$nextTick,保证子组件被渲染到父组件的DOM中后,在调用this.$refs.getCarRecord.getRecord()就不会有错了
更多推荐
已为社区贡献2条内容
所有评论(0)