vue的provide / inject向子孫組件傳遞數據/方法

1. vue的2.2.0版本新增的屬性:用以允許一個祖先組件向其所有子孫後代注入一個依賴,不論組件層次有多深,並在起上下游關係成立的時間裏始終生效。即祖先組件可(不論組件層次有多深)向其子孫組件傳遞事件,變量。參考官網:https://cn.vuejs.org/v2/api/#provide-inject

<template>
 <div>
    <childOne></childOne>
 </div>
</template>
 
<script>
 import childOne from '@/ChildOne'
 export default {
  name: "Parent",
  provide: {  //父組件,設置provide,可將變量,函數傳遞給其子孫組件中調用/使用。
    val: "demo",
    arr:[1,2,3],
    func:this.func,
  },
  methods:{
    func(){

    }
  },
  components:{
   childOne
  }
 }
<template>
 <div>
  {{parentProvide}}
  <childtwo></childtwo>
 </div>
</template>
 
<script>
 import childtwo from '@/ChildTwo'
 export default {
  name: "childOne",
  inject: ['val'],
  data() {
   return {
    parentProvide: this.val,  //接受父組件傳遞過來的變量
   }
  },
  mounted(){
    this.func();  //調用父組件傳遞過來的方法
  },
  components: {
   childtwo
  }
 }
</script>
<template>
 <div>
     <span v-for='(item,index) in arr' :key='index'></span>
 </div>
</template>
 
<script>
 export default {
  name: "childThird",
  inject: ['arr'],
  data() {
   return {
    arr: this.arr
   }
  }
 }
</script>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章