為深度嵌套的組件,父組件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>