vue.js 父組件主動獲取子組件的數據和方法、子組件主動獲取父組件的數據和方法

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

1.調用子組件的時候 定義一個refsass

//headerchild子組件名稱
<headerchild ref="headerChild"></headerchild>

2.在父組件裏面經過下面方法獲取子組件的數據和方法this

this.$refs.headerChild.屬性
this.$refs.headerChild.方法

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

在子組件裏面經過下面的方法獲取父組件屬性和方法spa

this.$parent.屬性
this.$parent.方法

代碼例子:code

//父組件
<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>
相關文章
相關標籤/搜索