vue依赖注入

改一个官网的例子
类似于react的context,后代组件要用声明一下就行,

<script src="https://unpkg.com/vue"></script>
<style>
h1{
  background:yellow;
}
h2{
  background:blue;
}
h3{
  background:pink;
}
</style>
<div id="dynamic-component-demo">
<google-map style="border:1px solid pink;">
  <google-map-region v-bind:shape="cityBoundaries" style="border:1px solid red;width:80%;">
    <google-map-markers v-bind:places="iceCreamShops"  style="border:1px solid yellow;width:60%;"></google-map-markers>
  </google-map-region>
</google-map>
</div>
<script>
Vue.component('google-map', { 
    template: `<div><h1 @click="changeMsg">我是祖父,googel-map,{{msg}}</h1><div>改变msg<input type=“text” v-model="msg" /></div><slot></slot></div>`,
  data(){
    return {
      msg:'问候你,你好,我是李云龙'
    }
  },
  provide: function () {
    return {
      getMap: function(){
      console.log('我来自祖父组件,要用我用inject就好啦,怎么感觉我像react中的context',this.msg)
    },
    msg:this.msg
  }
},
methods:{
  changeMsg(){
    this.msg = 'hello,i am zhanglijian!'
  }
}
})
Vue.component('google-map-region', { 
  props:["shape"],
  inject: ['getMap','msg'],
    template: `<div><h2 @click="getMap">我是父亲,gooel-map-region,{{msg}}</h2><p>{{shape}}</p><slot></slot></div>`
})
Vue.component('google-map-markers', {
  props:["places"],
  inject: ['getMap','msg'],
    template: `<div><h3 @click="getMap">我是儿子,gooel-map-makers,{{msg}}</h3><p>{{places}}</p></div>`
})
new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTab: 'Posts',
    tabs: ['Posts', 'Archive'],
    msg:'恭喜您中了我司一等奖,hiahiahia!',
    cityBoundaries:'滨江',
    iceCreamShops:'永辉超市'
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
})
</script>

2,并不是响应式的
如图,改变msg,子组件的并不会跟着改变


捕获.PNG
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容