ref / refs 的常规用法
1.获取 DOM 元素
在dom元素上添加 ref="名字", 可以通过 this.$refs.名字 来获取,这样就可以减少获取dom节点的消耗了
2.父组件直接接操作子组件的数据和方法
在导入的子组件上绑定 ref="名字" ,在父组件直接通过 this.$refs.名字 调用就可以使用子组件内的数据和方法
获取 DOM 元素(案例)
简单代码示例:
<template>
<div>
<h2 ref="test">dom元素的获取</h2>
</div>
</template>
<script>
export default {
mounted() {
const dom = this.$refs.test
console.log(dom);
},
};
</script>
效果示例图如下:
父组件直接接操作子组件的数据和方法(案例)
代码示例:
//子组件
<template>
<div>{{lcmsg}}</div>
</template>
<script>
export default {
data() {
return {
lcmsg: '我是子组件'
}
},
methods: {
watchMsg() {
this.lcmsg = '点我重新赋值'
}
}
}
</script>
//父组件
<template>
<div @click="getData">
<children ref="children"></children>
</div>
</template>
<script>
import children from 'components/children.vue'
export default {
components: {
children
},
data() {
return {}
},
methods: {
getData() {
//返回一个对象
this.$refs.children
//调用children的watchMsg方法
this.$refs.children.watchMsg()
}
}
}
</script>