首页 文章

如何在vuex商店中使用vue-resource($ http)和vue-router($ route)?

提问于
浏览
8

在我从组件的脚本中获取电影细节之前 . 该功能首先检查商店的电影ID是否与路线的参数电影ID相同 . 如果相同则不从服务器API获取电影,否则从服务器API获取电影 .

它工作正常 . 但现在我正试图从商店的变异中获取电影细节 . 但是我收到了错误

未捕获的TypeError:无法读取未定义的属性'$ route'

如何使用vue-router ($route) 访问params和vue-resource ($http) 从vuex store中的服务器API获取?

store.js:

export default new Vuex.Store({
    state: {
        movieDetail: {},
    },
    mutations: {
        checkMovieStore(state) {
            const routerMovieId = this.$route.params.movieId;
            const storeMovieId = state.movieDetail.movie_id;
            if (routerMovieId != storeMovieId) {
                let url = "http://dev.site.com/api/movies/movie-list/" + routerMovieId + "/";
                this.$http.get(url)
                    .then((response) => {
                        state.movieDetail = response.data;
                    })
                    .catch((response) => {
                        console.log(response)
                    });
            }
        },
    },
});

组件脚本:

export default {
    computed: {
        movie() {
            return this.$store.state.movieDetail;
        }
    },
    created: function () {
        this.$store.commit('checkMovieStore');
    },
}

2 回答

  • 2

    要在vuex存储中使用 $http$router ,您需要使用主vue实例 . 虽然我在回答实际问题后不会添加我推荐的内容 .


    main.js 或您创建vue实例的任何地方,例如:

    new Vue({ 
      el: '#app',
      router,
      store,
      template: '<App><App/>',
      components: {
        App
      }
    })
    

    或类似的东西,你也可能也添加了 vue-routervue-resource 插件 .

    对此做一点修改:

    export default new Vue({ 
      el: '#app',
      router,
      store,
      template: '<App><App/>',
      components: {
        App
      }
    })
    

    我现在可以在vuex商店中导入它,如下所示:

    //vuex store:
    import YourVueInstance from 'path/to/main'
    
    checkMovieStore(state) {
    const routerMovieId = YourVueInstance.$route.params.movieId;
    const storeMovieId = state.movieDetail.movie_id;
    if (routerMovieId != storeMovieId) {
      let url = "http://dev.site.com/api/movies/movie-list/" + routerMovieId + "/";
      YourVueInstance.$http.get(url)
        .then((response) => {
           state.movieDetail = response.data;
         })
         .catch((response) => {
           console.log(response)
         });
      }
    }
    

    并且作为Austio的答案,这个方法应该是 action ,因为 mutations 不是为处理异步而设计的 .


    现在开始采用推荐的方式 .

    • 您的 component 可以访问 route params 并将其提供给 action .
    methods: {
      ...mapActions({
        doSomethingPls: ACTION_NAME
      }),
      getMyData () {
        this.doSomethingPls({id: this.$route.params})
      }
    }
    
    • action 然后通过抽象的API服务文件(read plugins)进行调用
    [ACTION_NAME]: ({commit}, payload) {
       serviceWhichMakesApiCalls.someMethod(method='GET', payload)
         .then(data => {
            // Do something with data
         })
         .catch(err => {
            // handle the errors
         })
    }
    
    • 您的 actions 执行了一些异步作业并将结果提供给 mutation .
    serviceWhichMakesApiCalls.someMethod(method='GET', payload)
         .then(data => {
            // Do something with data
            commit(SOME_MUTATION, data)
         })
         .catch(err => {
            // handle the errors
         })
    
    • Mutations 应该是唯一修改 state 的人 .
    [SOME_MUTATION]: (state, payload) {
       state[yourProperty] = payload
    }
    

    Example 包含 endpoints 列表的文件,如果您具有不同的api endpoints ,例如:test,staging,production等,则可能需要它们 .

    export const ENDPOINTS = {
      TEST: {
        URL: 'https://jsonplaceholder.typicode.com/posts/1',
        METHOD: 'get'
      }
    }
    

    以及实现 Vue.http 作为服务的主文件:

    import Vue from 'vue'
    import { ENDPOINTS } from './endpoints/'
    import { queryAdder } from './endpoints/helper'
    /**
    *   - ENDPOINTS is an object containing api endpoints for different stages.
    *   - Use the ENDPOINTS.<NAME>.URL    : to get the url for making the requests.
    *   - Use the ENDPOINTS.<NAME>.METHOD : to get the method for making the requests.
    *   - A promise is returned BUT all the required processing must happen here,
    *     the calling component must directly be able to use the 'error' or 'response'.
    */
    
    function transformRequest (ENDPOINT, query, data) {
      return (ENDPOINT.METHOD === 'get')
          ? Vue.http[ENDPOINT.METHOD](queryAdder(ENDPOINT.URL, query))
          : Vue.http[ENDPOINT.METHOD](queryAdder(ENDPOINT.URL, query), data)
    }
    
    function callEndpoint (ENDPOINT, data = null, query = null) {
      return new Promise((resolve, reject) => {
        transformRequest(ENDPOINT, query, data)
          .then(response => { return response.json() })
          .then(data => { resolve(data) })
          .catch(error => { reject(error) })
      })
    }
    
    export const APIService = {
      test () { return callEndpoint(ENDPOINTS.TEST) },
      login (data) { return callEndpoint(ENDPOINTS.LOGIN, data) }
    }
    

    queryAdder在重要的情况下,我使用它来将params添加到url .

    export function queryAdder (url, params) {
      if (params && typeof params === 'object' && !Array.isArray(params)) {
        let keys = Object.keys(params)
        if (keys.length > 0) {
          url += `${url}?`
          for (let [key, i] in keys) {
            if (keys.length - 1 !== i) {
              url += `${url}${key}=${params[key]}&`
            } else {
              url += `${url}${key}=${params[key]}`
            }
          }
        }
      }
      return url
    }
    
  • 11

    所以有一些东西,$ store和$ route是Vue实例的属性,这就是为什么在Vuex实例中访问它们不起作用的原因 . 此外,突变是同步的,你需要的是行动

    • Mutations =>给定状态和一些参数的函数会改变状态

    • Action =>执行像http调用之类的异步操作,然后将结果提交到突变

    因此,创建一个调度http的动作 . 请记住,这是伪代码 .

    //action in store
    checkMovieStore(store, id) {
      return $http(id)
        .then(response => store.commit({ type: 'movieUpdate', payload: response })
    }
    
    //mutation in store
    movieUpdate(state, payload) {
      //actually set the state here 
      Vue.set(state.payload, payload)
    }
    
    // created function in component
    created: function () {
       return this.$store.dispatch('checkMovieStore', this.$route.params.id);
    },
    

    现在,您创建的函数使用id调用checkMovieStore操作,该id执行http调用,一旦完成,它将使用值更新存储 .

相关问题