父組件主動獲取子組件的數據和方法
1.調用子組件的時候 定義一個ref
<headerchild ref="headerChild"></headerchild>
2.在父組件裏面通過
this.$refs.headerChild.屬性
this.$refs.headerChild.方法
子組件主動獲取父組件的數據和方法
在子組件裏面通過
this.$parent.屬性
this.$parent.方法
演示代碼:
//父組件
<template>
<div id="header">
<headerchild ref="headerChild"></headerchild>
<button @click="getChild()">父組件獲取子組件的數據和方法</button>
</div>
</template>
<script>
import HeaderChild from './HeaderChild'
export default {
data () {
return {
title:'我是父組件的數據'
}
},
methods: {
getChild (){
console.log(this.$refs.headerChild.name)
},
run (){
console.log("我是父組件裏面的方法")
}
},
components: {
'headerchild': HeaderChild
}
}
</script>
<style lang="sass" scoped>
</style>
//子組件
<template>
<div id="headerchild">
<button @click="getParent()">獲取父組件的數據和方法</button>
</div>
</template>
<script>
export default {
data () {
return {
name:'我是子組件裏面的數據'
}
},
methods:{
getParent(){
console.log(this.$parent.title) /*獲取整個父組件*/
this.$parent.run()/*獲取父組件的方法*/
}
},
props:['title','run','home'] /*通過props接收父組件傳遞過來的數據 */
}
</script>