ref与$res的关系
1、如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;
2、如果用在子组件上,引用就指向组件实例:
第一、ref标记DOME元素,$refs获取被标记的元素
<template>
<div id="app">
<div ref="mainBox">
<h1>在ref中的DOM元素</h1>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log(this.$refs.mainBox)
//输出:<div><h1>在ref中的DOM元素</h1></div>
}
};
</script>
第二、$refs可以获取子组件中的data和方法
子组件
<template>
<div>
{{ title}}
</div>
</template>
<script>
export default {
data() {
return {
title: "hello world"
}
},
methods: {
showMsg() {
console.log("showMsg方法被调用")
}
}
}
*********************************
父组件
<template>
<div id="app">
<HelloWorld ref="boxMain"/>
<button @click="getMain">获取子组件中的值</button>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
components: {
HelloWorld
},
methods: {
getMain() {
//调用子组件data
console.log(this.$refs.boxMain.msg)
//调用子组件方法
this.$refs.boxMain.showMsg();
}
}
};
</script>
</script>