将组件的标签添加一个ref=“xxx” ,然后父组件使用子组件直接this.refs.xxx.xxx
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>vue中的ref</title>
</head>
<body>
<div id="app">
<h1>我是一个vue项目</h1>
<div class="container" ref="c">
<p ref="p">我是一句话</p>
<hw ref="jj"></hw>
<button @click="dddd">
点击父组件的按钮,打印子组件的msg,同时调用子组件hw中的h方法
</button>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
<script>
const hw = {
template: `<div class="hw">
<h5>我是一个自定义组件</h5>
<hr/>
</div>`,
data() {
return {
msg: "动物园里有什么?",
};
},
mounted() {
console.group("hw组件");
console.log(this.$root.$el);
console.groupEnd();
},
methods: {
h() {
console.log("我是hw中的h方法");
},
},
};
new Vue({
el: "#app",
components: {
hw,
},
created() {},
mounted() {
// $el 获取当前组件的dom元素
// $refs 获取当前组件中设置了ref属性的标签
// $root获取父组件的内容,如果没有父组件,显示自己的内容
console.log(this.$el);
console.log(this.$el.querySelector("p"));
console.log(this.$refs);
console.log(this.$refs.p);
console.log(this.$root.$el);
},
methods: {
dddd() {
this.$refs.jj.h();
console.log(this.$refs.jj.msg);
},
},
});
</script>
</body>
</html>