如何在Vuex Action中传递可变API端点?
如何在Vuex Action中传递不同的API端点URL实现复用
当然可以实现!你完全不需要写多个仅端点不同的重复Action,只需要给Action传递参数就能复用同一个函数。我来帮你调整代码,一步步实现这个需求:
第一步:修改Vuex Action,接收端点参数
我们需要给getMovies Action添加一个参数,用来接收不同的API端点。同时建议把API密钥单独提取出来,避免在多个端点中重复书写,方便后续维护:
import axios from 'axios' const API_KEY = '你的API密钥' // 单独管理API密钥,更易维护 export const topTwentyEndpoint = `https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=${API_KEY}` export const theatresEndpoint = `https://api.themoviedb.org/3/discover/movie?primary_release_date.gte=2014-09-15&primary_release_date.lte=2014-10-22&api_key=${API_KEY}` export const state = () => ({ posts: [], }) export const mutations = { setMovies(state, posts) { state.posts = posts }, } export const getters = {} export const actions = { // 给Action添加endpoint参数,并设置默认值兼容原有调用逻辑 getMovies({ commit }, endpoint = topTwentyEndpoint) { axios.get(endpoint) .then((response) => { commit('setMovies', response.data.results) }) .catch(error => { // 新增错误处理,方便排查请求失败问题 console.error('获取电影数据失败:', error) }) }, }
第二步:修改组件,传递对应端点到Action
在组件中,我们需要给每个按钮绑定点击事件时,传递对应的API端点。首先导入Vuex中定义的端点常量,然后在submitForm方法中接收这个参数并传给Action:
<template> <form id="formGetMovies" class="flex flex-col items-start w-3/4 pt-5 get-movies" > <div class="flex buttons__row"> <button class="py-3 mt-2 mr-5 text-white bg-red-700 rounded-md hover:bg-red-800 px-7 btn btn__submit btn-disabled" :class="{ disabled: moviesShown }" :disabled="moviesShown" @click.prevent="submitForm(topTwentyEndpoint)" > Top 20 </button> <button class="py-3 mt-2 text-white bg-red-700 rounded-md hover:bg-red-800 px-7 btn btn__submit btn-disabled" :class="{ disabled: moviesShown }" :disabled="moviesShown" @click.prevent="submitForm(theatresEndpoint)" > In Theatres Now </button> </div> </form> </template> <script> // 根据你的项目实际路径导入端点常量 import { topTwentyEndpoint, theatresEndpoint } from '@/store/modules/movies' export default { name: 'MoviesForm', data() { return { moviesShown: false, topTwentyEndpoint, theatresEndpoint } }, methods: { submitForm(endpoint) { // 把端点参数传递给Action this.$store.dispatch('movies/getMovies', endpoint) this.moviesShown = true }, }, } </script>
额外优化建议
- 后续如果需要新增更多电影分类,只需要在Vuex中添加新的端点常量,然后在组件中新增对应按钮并传递新端点即可,完全不需要修改
getMoviesAction的代码,扩展性很强。 - 可以考虑把所有API端点统一放在一个配置文件中管理,比如
src/config/api.js,这样项目中所有用到API的地方都可以引用这个文件,进一步提升可维护性。
内容的提问来源于stack exchange,提问作者hendy0817
相关产品推荐
相关产品推荐

