vue之provide/inject

24 篇文章 0 订阅
20 篇文章 0 订阅

经测试发现,当provide提供为对象或者是某个方法时,子对象取值才会是响应式的。
在这里插入图片描述

父组件代码 parent.vue
<template>
  <div>
    <Child />
    <button
      class="btn"
      @click="clickTest"
    >
      点击我
    </button>
  </div>
</template>

<script>
import Child from './child'
export default {
  name: '',

  components: { Child },

  mixins: [],

  props: {},
  provide () {
    return {
      objTest: {
        status: this.status
      },
      stringTest: this.on,
      fnTest: this.onFn
    }
  },
  data () {
    return {
      on: true,
      status: {
        on: true
      }
    }
  },

  computed: {},

  watch: {},

  created () {

  },

  mounted () {

  },

  destroyed () {},

  methods: {
    clickTest () {
      this.status.on = !this.status.on
      this.on = !this.on
    },
    onFn () {
      return this.on
    }
  }
}
</script>

<style lang="less" scoped>
.btn{
background:#FF700A;
color:#fff;
margin-top:10px;
padding:10px;
}
</style>

子组件代码 child.vue
<template>
  <div style="background:#fff;">
    <h3 class="item">
      我是测试inject为对象时:<span>{{ objTest.status.on }}</span>
    </h3>
    <h3 class="item">
      我是测试inject为方法时:{{ fnTest() }}
    </h3>
    <h3 class="item">
      我是测试inject为字符串时:{{ stringTest }}
    </h3>
  </div>
</template>

<script>
export default {
  name: '',

  components: {},

  mixins: [],

  props: {},
  
  inject: ['objTest', 'stringTest', 'fnTest'],
  
  data () {
    return {}
  },

  computed: {},

  watch: {},

  created () {

  },

  mounted () {},

  destroyed () {},

  methods: {}
}
</script>

<style lang="less" scoped>
.item{
    font-size:14px;
    padding:10px;
}
</style>

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值