Returning data from store.js in vuejs returns TypeError

前端 未结 1 746
悲&欢浪女
悲&欢浪女 2021-01-28 11:43

I have a store.js file which sends an api request and gets responses using axios, the api is tested and working perfectly. store.js contains this code :

import V         


        
相关标签:
1条回答
  • 2021-01-28 11:46

    Let me show you an example about how to use the Vuex store:

    // 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)
    });
    

    Now the store.js file:

    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
    });
    

    And a component to call the action and show the information:

    // 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>
    

    I didn't test it, but this is the idea behind a vuex store and how to use it, if somebody sees an error, please let me know to update the answer (thanks).

    Hope you can update your code with this information and it can work properly.

    Also, Scrimba has a free course that could help you to extend your knowledge about Vuex, check it here

    0 讨论(0)
提交回复
热议问题