vue3-provideinject注⼊
为深度嵌套的组件,⽗组件provide提供数据来源,⼦组件inject开始使⽤这个数据
provide: {
todoLength: dos.length // 将会导致错误 'Cannot read property 'length' of undefined`
},
//要访问组件实例,需要将provide转换为返回对象函数
provide() {
return {
todoLength: dos.length
}
},
setup中使⽤
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>
import { inject } from'vue'
export default {
vue中reactive
setup() {
const userLocation = inject('location', 'The Universe')
const userGeolocation = inject('geolocation')
return {
userLocation,
userGeolocation
}
}
}
</script>
//增加响应,使⽤ref, reactive 如果任何⼀个属性发⽣变化,该MyMarker组件也将⾃动更新<!-- src/components/MyMap.vue -->
<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
})
provide('location', location)
provide('geolocation', geolocation)
}
}
</script>