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>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。