在 Vue3 中,使用 Vuex 发送异步请求可以按照以下步骤进行:\n\n1. 在store文件夹中创建一个weather.js文件,用于定义天气状态数据和异步请求的方法。\n\njavascript\nimport axios from 'axios';\n\nconst state = {\n weather: null\n};\n\nconst mutations = {\n setWeather(state, weather) {\n state.weather = weather;\n }\n};\n\nconst actions = {\n async fetchWeather({ commit }, city) {\n try {\n const response = await axios.get(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}`);\n commit('setWeather', response.data);\n } catch (error) {\n console.error(error);\n }\n }\n};\n\nexport default {\n state,\n mutations,\n actions\n};\n\n\n2. 在main.js中引入createStore方法,并将weather模块添加到store中。\n\njavascript\nimport { createApp } from 'vue';\nimport { createStore } from 'vuex';\nimport weather from './store/weather';\n\nconst store = createStore({\n modules: {\n weather\n }\n});\n\nconst app = createApp(App);\n app.use(store);\n app.mount('#app');\n\n\n3. 在组件中使用mapActions辅助函数将fetchWeather方法映射到组件中,并调用它来获取天气状态数据。\n\njavascript\n<template>\n <div>\n <button @click="getWeather">获取天气</button>\n <div v-if="weather">\n <h2>{{ weather.location.name }} 天气</h2>\n <p>当前温度:{{ weather.current.temp_c }}℃</p>\n <p>天气状况:{{ weather.current.condition.text }}</p>\n </div>\n </div>\n</template>\n\n<script>\nimport { mapActions } from 'vuex';\n\nexport default {\n methods: {\n ...mapActions('weather', ['fetchWeather']),\n getWeather() {\n this.fetchWeather('某某城市'); // 替换为具体的城市名称\n }\n },\n computed: {\n weather() {\n return this.$store.state.weather.weather;\n }\n }\n};\n</script>\n\n\n上述代码中的fetchWeather方法使用axios库发送异步请求获取天气数据,并将数据保存到state中的weather属性中。mapActions辅助函数将fetchWeather方法映射到组件的methods中,通过调用this.fetchWeather方法来触发异步请求。在模板中,使用v-if指令判断weather是否存在,若存在则显示天气信息。\n\n请注意,上述代码中的https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}是一个示例的天气API接口,需要替换为真实的API地址,并将YOUR_API_KEY替换为你的实际API密钥。

Vue3 中使用 Vuex 发送异步请求获取天气数据 - 示例教程

原文地址: https://www.cveoy.top/t/topic/pxj2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录