首页 > 解决方案 > 从 vuejs 中的 store.js 返回数据返回 TypeError

问题描述

我有一个 store.js 文件,它发送一个 api 请求并使用 axios 获取响应,该 api 已经过测试并且运行良好。store.js 包含以下代码:

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import cUser from './modules/User';
import UI from './modules/UI';
Vue.use(Vuex)
export default new Vuex.Store({
    data: function () {
        return {
          responsedata: []
        };
      },
viewresults: async (commit, payload)=>{
            let token =localStorage.getItem('token');
            let username= payload.username;
            await axios.post('search',{token, username}).then(response => {
               this.responsdata = response.data;
            }).catch(er=>{
                    console.log(er);
                });

我在其他使用它的文件中有这个功能:

search(){
          console.log('search clicked');
          console.log(this.username);
          this.responsedata = this.$store.dispatch('viewresults',{
            username: this.username,
          });
          console.log(this.responsedata);
          },
    }

但我在浏览器控制台中收到此错误:

TypeError:无法设置未定义的属性“响应数据”

似乎store.js中的 viewresult 看不到数据返回函数中定义的 responsedata 变量。

标签: javascriptvue.js

解决方案


让我向您展示一个有关如何使用 Vuex 商店的示例:

// main.js
import Vue from 'vue';
import App from './App.vue';
import store from '@/store/index';

new Vue({
  el: '#app',
  store,
  components: {
    App
  },
  render: h => h(App)
});

现在 store.js 文件:

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios'

Vue.use(Vuex);

const state = {
  responseData: []
}

const mutations = {
  setResponse(state, data) {
    state.responseData = data;
  }
}

const actions = {
  async viewResults({ commit }, payload) {
    let token =localStorage.getItem('token');
    let username= payload.username;
    await axios.post('search', { token, username }).then(response => {
      commit('setResponse', response.data);
    }).catch(er=>{
      console.log(er);
    });
  }
}

export const store = new Vuex.Store({
  state,
  mutations,
  actions
});

以及一个调用动作并显示信息的组件:

// SearchAndShowData.vue component

<template>
  <div>
    <button click="search">
      Search
    </button>

    {{ responseData}}
  </div>
</template>
<script>
  import {mapActions, mapState} from 'vuex';
  export default {
    name: "SearchAndShowData",
    data: () => ({
      username: "Andres",
    }),
    computed() {
      // Expose the state.responseData object as responseData
      ...mapState(['responseData']) // If you want to preprocess the data, use create a getter and use mapGetters
      // As a computed property, it will be updated always that responseData has any change
    },
    methods: {
      ...mapActions(["viewResults"]), // Expose the viewResults action as a method, call it with this.viewResults
      search() {
        this.viewResults({username: this.username })
      }
    }
  }
</script>

我没有测试它,但这是 vuex 商店背后的想法以及如何使用它,如果有人看到错误,请告诉我更新答案(谢谢)。

希望您可以使用此信息更新您的代码,并且它可以正常工作。

此外,Scrimba 有一个免费课程,可以帮助您扩展有关 Vuex 的知识,请在此处查看


推荐阅读