vue3x 使用provide inject

官网链接: link.

在3x中使用provide inject需要先引入
provide有两个参数:1.属性的名称(类型) 2.物业价值
inject有两个参数:1.要注入的属性的名称 2.默认值(可选)

<template>
  <MyMarker />
</template>

<script>
import { provide } from 'vue'
import MyMarker from './MyMarker.vue

export default {
  components: {
    MyMarker
  },
  setup() {
    provide('location', 'North Pole')
    provide('geolocation', {
      longitude: 90,
      latitude: 135
    })
  }
}
</script>

在接收时可以对其进行重构

<script>
import { inject } from 'vue'

export default {
  setup() {
    const userLocation = inject('location', 'The Universe')
    const userGeolocation = inject('geolocation')

    return {
      userLocation,
      userGeolocation
    }
  }
}
</script>

使其变成响应式数据,当他任意一个属性发生变化时,在接收时也会自动更新

<template>
  <MyMarker />
</template>

<script>
import { provide, reactive, ref } from 'vue'
import MyMarker from './MyMarker.vue

export default {
  components: {
    MyMarker
  },
  setup() {
    const location = ref('North Pole')
    const geolocation = reactive({
      longitude: 90,
      latitude: 135
    })
    const updateLocation = () => {  //创建函数
      location.value = 'South Pole'
    }
    provide('location', location)
    provide('geolocation', geolocation)
    provide('updateLocation', updateLocation) //传递函数
  }
}
</script>
<!-- src/components/MyMap.vue -->
<template>
  <MyMarker />
</template>

<script>
import { provide, reactive, readonly, ref } from 'vue'
import MyMarker from './MyMarker.vue

export default {
  components: {
    MyMarker
  },
  setup() {
    const location = ref('North Pole')
    const geolocation = reactive({
      longitude: 90,
      latitude: 135
    })

    const updateLocation = () => {
      location.value = 'South Pole'
    }

    provide('location', readonly(location))
    provide('geolocation', readonly(geolocation))
    provide('updateLocation', updateLocation)
  }
}
</script>
<!--MyBook.vue-->
<template>
<div>
  <button @click="uptext">test</button>
<!--直接用test函数修改来自父组件的readers,控制台出现警告 -->
  <button @click="updatelocation">updatelocation</button>
<!-- 调用来自父组件的updatelocation,修改location对象,允许修改,无警告-->
</div>
</template>
<script>
import { inject} from 'vue';
export default {
    name:'MyBook',
    setup()
    {
        const readers=inject('readers');
        const updatelocation=inject('updatelocation');
        return{updatelocation,readers}
    },
    methods:
    {
        uptext()
        {
            this.readers=66;//直接修改来自父组件注入的readers,控制台出现警告
        }
    }
}
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值