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>

  運行結果


免責聲明!

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



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