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

标签 javascript vuejs2 vue-router vue-resource vuex

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

它运行良好。但现在我正试图从商店的突变中获取电影细节。但是我收到错误

Uncaught TypeError: Cannot read property '$route' of undefined

如何使用 vue-router ($route) 访问参数和 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');
    },
}

最佳答案

要在您的 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 不是为处理异步而设计的。


现在介绍推荐的方法。

  1. 您的组件可以访问路由参数并将其提供给action

     methods: {
       ...mapActions({
         doSomethingPls: ACTION_NAME
       }),
       getMyData () {
         this.doSomethingPls({id: this.$route.params})
       }
     }
    
  2. action 然后通过抽象的 API 服务文件 (read plugins) 进行调用

     [ACTION_NAME]: ({commit}, payload) {
        serviceWhichMakesApiCalls.someMethod(method='GET', payload)
          .then(data => {
             // Do something with data
          })
          .catch(err => {
             // handle the errors
          })
     }
    
  3. 您的 actions 执行一些异步工作并将结果提供给 mutation

     serviceWhichMakesApiCalls.someMethod(method='GET', payload)
          .then(data => {
             // Do something with data
             commit(SOME_MUTATION, data)
          })
          .catch(err => {
             // handle the errors
          })
    
  4. Mutations 应该是唯一修改您的state 的。

     [SOME_MUTATION]: (state, payload) {
        state[yourProperty] = payload
     }
    

例子 一个包含端点列表的文件,如果您有不同的部署阶段具有不同的 api 端点,例如:测试、暂存、生产等,您可能需要它。

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 以防它很重要,我用它来向 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
}

关于javascript - 如何在 vuex 商店中使用 vue-resource ($http) 和 vue-router ($route)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42560318/

相关文章:

javascript - 使用 bootstrap-vue b-nav-item 将 props 传递给 vue-router

javascript - 闭包语法: (function a(){})() == (function a(){}())?

javascript - 在 P5.js 中创建元素对象

javascript - 如何使用 javascript 创建导航菜单?单击菜单选项后如何平滑滚动到部分?

javascript - 获取 Google map 上的所有图像详细信息

javascript - 将 props 传递给 vue2 组件

vue.js - 父子vue之间的异步生命周期

ios - 是什么导致了这个 vue-router 异步组件错误 - TypeError : undefined is not an object (evaluating 't.__esModule' )?

vue.js - vue-router 如何使用 hash 推送({name :"question"})?

unit-testing - 如何使用 '@vue/test-utils' 测试 VueRouter 的 beforeRouteEnter ?