provide inject越級得實例

在這裏插入圖片描述

<template>
  <div>
    <child ref="chil">
        <span slot-scope="props" ref="span"> {{props.value}} {{props.aaa}} {{value}}</span>
       
    </child>
     value:<input type="text" v-model="value">
     newValue: <input type="text" v-model="newValue.a">
  </div>
</template>

<script>
import child from "./child.vue";
export default {
    components:{
        child
    },
    provide(){ //通過provide,提供實例和實例的一個屬性
        // const data = {}
        // Object.defineProperties(data,'newValue',{
        //     get:()=>this.newValue,
        //     enumerable:true
        // })
        return {
            yeye:this,
            value:this.value,
            newValue:this.newValue
        }
    },
    data(){
        return {
            value:'123',
            newValue:{
                a:1
            }
        }
    },
    mounted(){
        // this.hahha()
        console.log(this.$refs.chil,this.$refs.span,this.$refs.chil.value)
    },
    methods :{
        hahha:function(){
            alert(1)
        }
    }
};
</script>

<style>
</style>
<template>
  <div :style="style">
      <slot :value="value" aaa=111></slot>
      <childs></childs>
  </div>
</template>

<script>
import childs from "./childs.vue"
export default {
    name:'child',
    components:{
        childs
    },
    data(){
        return {
            style:{
                width:'200px',
                height:'200px',
                border:'1px solid #ccc'
            },
            value:'caomponent value'
        }
    }
}
</script>

<style>

</style>
<template>
  <div>childs components

      <h1>{{this.value}}</h1>
      <h2>{{this.newValue.a}}</h2>
      <button @click="getIndexTwo">獲取爺爺組建值</button>
  </div>
 
</template>

<script>
export default {
inject:['yeye','value','newValue'],
mounted(){
  
    // this.yeye.hahha()
}
,
methods:{
    getIndexTwo:function(){
        //   console.log(this.yeye)
    console.log(this.value)
    console.log(this.newValue)
    }
}
}
</script>

<style>

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