【问题标题】:vue.js move method from .vue to vuex storevue.js 将方法从 .vue 移动到 vuex 商店
【发布时间】:2021-05-28 22:13:51
【问题描述】:

场景: 在user.js 我有:

import * as mutationTypes from "../mutation-types";
import {user} from "./user_data";

export const state = {
  user: user
  ...
}

export const getters = {
  user: (state) => state.user,
...
};

export const mutations = {
  [mutationTypes.SET_USER]: (state, payload) => {
    state.user=payload;  
  },
  ...
  );
  
  export const actions = {
  setUser: ({ commit }, payload) => {
    commit(mutationTypes.SET_USER, payload);
  },
  ...
  );
  
  export default {
  state,
  getters,
  mutations,
  actions,
};

现在我想将几个页面中使用的方法从 .vue 页面移动到这个商店页面: 所以我在 user.js 操作中添加了以下内容:

getUser: async ({ commit }) =>{
    this.user.loading=true;    
    try{
        const res = await this.$http.post('/ajax/settings/settings_read.php');
        if (res.data.errorid=='0')
        { 
          let payload=res.data.user;
          commit(mutationTypes.SET_USER, payload);
        }
        else
        {
          this.$router.push('/auth/login').catch(() => {});
        }      
    } catch(e)
    {
      console.log(e);
    }
    this.user.loading=false;    
},

在 .vue 页面中(实际上我尝试了可能在多个地方添加 async/await 的不同解决方案)

import { mapActions } from "vuex";
...
  created(){
      this.$store.dispatch("getUser"); 
  },

但不起作用。

能否建议将方法移动到 vuex 存储的正确方法?

【问题讨论】:

  • 你能对不工作的部分进行更详细的描述吗?你有错误吗?有什么事情发生吗?什么都没有发生吗?
  • 这可能不是您的直接问题,但您正在双重导出您的商店状态/getters/mutations/actions。您应该要么单独导出商店属性,将它们作为对象导出,但不能同时导出。
  • @zcoop98 谢谢。你的意思是我应该在const 之前删除所有export 或完全删除export default { state, getters, mutations, actions,};
  • 我认为您实际上可以做到;我更熟悉导出对象,但你更熟悉的工作正常:)
  • oh.. 如何同时删除两者:-( 其实我对任何解决方案都不是很熟悉无论如何,我现在得到的错误(经过一些更改)是Cannot read property '$http' of undefined,其中this.$http.post(...) 是@ 987654330@,但axios 没有在这个user.js 中定义,而是在main.js

标签: vuejs2 vuex


【解决方案1】:

看起来 this.user 是对您所在州的用户的引用,因此

 this.user.loading=true;    

会改变突变之外的状态。

【讨论】:

    猜你喜欢
    • 2018-09-08
    • 2018-11-20
    • 2021-10-20
    • 2016-09-09
    • 2022-09-23
    • 2017-12-18
    • 2020-02-05
    • 1970-01-01
    • 2021-04-10
    相关资源
    最近更新 更多