为深度嵌套的组件,父组件provide提供数据来源,子组件inject开始使用这个数据
provide: { todoLength: this.todos.length // 将会导致错误 'Cannot read property 'length' of undefined` }, //要访问组件实例,需要将provide转换为返回对象函数 provide() { return { todoLength: this.todos.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 {
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>