PA-*_*-GW 3 vue.js vuejs3 vue-composition-api
我正在使用 Vue 3 组合 api 并通过检索天气数据,async/await fetch并在 Chrome 开发工具中收到 200 响应和请求中的数据。
在接收数据并进行调用的组件中,我有一个provide方法,然后我将inject数据放入另一个输出组件中。问题出在inject组件上。ed 变量的值inject始终为 null,并且不会在 Vue 开发工具中更新,因此我的数据永远不会输出到屏幕。我浏览了文档,代码几乎相同,但我无法让它工作。任何人都可以看到一个明显的问题吗?
接收组件
setup () {
async function getCurrentWeather () {
const response = await fetch(`${baseWeatherApiUrl}q=${userInput.value}`);
userInput.value = null;
return weatherData.value = await response.json();
}
const returnedWeatherData = reactive(weatherData);
provide('returnedWeatherData', returnedWeatherData);
return {
getCurrentWeather,
userInput,
weatherData
}
}
Run Code Online (Sandbox Code Playgroud)
输出组件
setup () {
//Provide default of empty object in case no results exist
const weatherData = inject('returnedWeatherData');
console.log(weatherData) //No output even when making a new request to the weather api
return {
weatherData
}
}
Run Code Online (Sandbox Code Playgroud)
作为一个单独的测试,我尝试对provide/inject文档中找到的值进行硬编码,但geolocation注入时仍然为空。
provide('geolocation', {
longitude: 90,
latitude: 135
})
Run Code Online (Sandbox Code Playgroud)
const userGeolocation = inject('geolocation')
console.log(userGeolocation) // Nothing logged
return {
weatherData,
userGeolocation
}
Run Code Online (Sandbox Code Playgroud)
-ed参数provide应该是ref本身(不包含在 中reactive()):
// Parent.vue\nexport default {\n setup () {\n const weatherData = ref()\n\n // \xe2\x9d\x8c\n // const returnedWeatherData = reactive(weatherData);\n // provide(\'returnedWeatherData\', returnedWeatherData);\n\n // \xe2\x9c\x85\n provide(\'returnedWeatherData\', weatherData);\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n并且子组件console.log()不会setup()自动再次被调用。您应该将该调用包装起来,watchEffect()以便在更改时确实会调用它ref:
// Child.vue\nimport { inject, watchEffect } from \'vue\'\n\nexport default {\n setup () {\n const weatherData = inject(\'returnedWeatherData\')\n\n // \xe2\x9d\x8c\n //console.log(\'new weatherData\', weatherData.value)\n\n // \xe2\x9c\x85\n watchEffect(() => {\n console.log(\'new weatherData\', weatherData.value)\n })\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n