vue中父组件主动获取子组件的数据和方法, 子组件主动获取父组件的数据和方法
Home.vue
<template>
<div id="home">
<!--<v-header :_title="title" :homemsg="msg" :homerun="run" :_home="this"></v-header>-->
<!--<v-header :_title="title" ></v-header>-->
<v-header ref="header"></v-header>
首页组件
<button @click="getChildData()">获取子组件的数据和方法</button>
</div>
</template>
<script>
/* 父组件给子组件传值
1、父组件调用子组件的时候,动态绑定属性 <v-header :_title="title"></v-header>
2、在子组件里面通过props接收父组件传过来的数据
props:["_title"]
props:{"_title" :"String"}
3、直接在子组件里面使用
父组件主动获取子组件的数据和方法
1、调用子组件的时候定义一个ref
<v-header ref="header"></v-header>
2、在父组件里面通过
this.$ref.header.属性
this.$ref.header.方法
子组件主动获取父组件的数据和方法
this.$parent.数据
this.$parent.方法 */
import Header from './Header.vue';
export default {
name: "Home",
data(){
return {
// msg:'我是一个Home组件',
title:"asddd",
msg:'我是home组件'
}
},
methods:{
run(){
console.log('这是父组件的run方法' )
},
getChildData(){
console.log(this.$refs)
console.log(this.$refs.header.msg)
this.$refs.header.run()
}
},
components: {
'v-header' :Header
}
}
</script>
<style scoped>
</style>
Header.vue
<template>
<div>
<h2>这是头部组件</h2>
<!--<button @click="homerun('123')">执行父组件的方法</button>-->
<!--<button @click="getParent()">获取父组件的数据和方法</button>-->
<button @click="getParentData()">获取父组件的数据和方法</button>
</div>
</template>
<script>
export default {
name: "Header",
data() {
return {
msg:'子组件的msg'
}
},
methods: {
run(){
console.log('我是子组件的run方法')
},
getParentData(){
/*子组件主动获取父组件的数据和方法
this.$parent.数据
this.$parent.方法 */
// console.log(this.$parent.msg)
this.$parent.run() //调用父组件的run方法
}
},
}
</script>
<style scoped>
</style>
运行结果


浙公网安备 33010602011771号