创建一个子组件
代码语言:javascript复制<template>
<div>
<button @click="getParent()">获取父组件信息</button>
</div>
</template>
<script>
export default {
name: "poster",
data() {
return {
sonMsg: "这是子组件的值"
};
},
mounted() {},
methods: {
getSon() {
console.log("这是子组件的方法");
},
getParent() {
//子组件通过$parent获取父组件的方法和值
this.$parent.getFa();
console.log(this.$parent.faMsg);
}
}
};
</script>
创建一个父组件,把子组件引入到父组件中去
代码语言:javascript复制<template>
<div class="home">
<poster ref="poster" />
</div>
</template>
<script>
import poster from "@/components/poster.vue";
export default {
name: "home",
components: {
poster
},
data() {
return {
faMsg: "这是父组件的值"
};
},
mounted() {
// 获取到子组件的值和方法
this.$refs.poster.getSon();
console.log(this.$refs.poster.sonMsg);
},
methods: {
getFa() {
console.log("这是父组件的方法");
}
}
};
</script>