13.子組件主動獲取父組件的數據和方法


子組件主動獲取父組件的數據和方法

1.父組件Home.vue

<template>
    <div>
        <h2>{{msg}}</h2>
        
        <v-header></v-header>
        
    </div>
</template>
<script>
import Header from "./Header.vue";
export default {
  name: 'home',  
  data () {
    return {
        msg:'首頁組件',
        title:'父組件'
    }
  },
  methods:{
    run(){
      alert('父組件方法')
    }
  },
  components:{
    'v-header':Header
  }
}
</script>
<style lang="scss" scoped>
h2{
    color: red;
}
</style>

2.子組件Header.vue

<template>
    <div>
        <h2>{{msg}}</h2>
        <button @click="getData()">獲取父組件數據</button>
        <button @click="getFunction()">獲取父組件的方法</button>
    </div>
</template>
<script>
export default {
  name: 'Header',  
  data () {
    return {
        msg:'頭部組件',
        title:'子組件'
    }
  },
  methods:{
      getData(){
          console.log(this.$parent.title)  
      },
      getFunction(){
          this.$parent.run()
      }
  }
}
</script>
<style lang="scss" scoped>
h2{
    color: green;
}
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM