官网链接: 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>