0

想问下,vuex在一个store.js里面,想把actions里面定义的一个方法赋值给state里一个属性,怎么搞,代码如下, //我要把actions里的makeAccessId赋值给这个makeAccessId
`

state: {
    seie:{
        config:{
            token_key:'mgt_token',
            serviceHost:"http://192.168.1.54:9090",
            host:"http://192.168.1.54:9080"
        }
    },
    menu: "layer", 
    user: null,
    makeAccessId: //我要把actions里的makeAccessId赋值给这个makeAccessId
},
mutations: {
    setMenu(state, val) {
        state.bread = null;
        state.menu = val;
    },
    setUser(state, val) {
        state.user = val;
    }
    
},
actions: {
    makeAccessId:() => {
        var text = "";
        var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
    
        for( var i=0; i < 9; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    
        return text;
    }
},
getters: {
    getAjax: state => {
        return L.SEIE.Ajax;
    },
    getMenu(state) {
        return state.menu;
    },
    getUser(state) {
        let user = process.env.NODE_ENV === 'development' ? {
            "data_id": 1,
            "id": 1,
            "name": "admin",
            "timezone": "Asia/Shanghai",
            "language": "ENUS",
            "token": "fe7a83696b2a3d369edf28d8a9267721",
            "gender": 0,
            "account": "admin",
            "right_list": [{
                "right_update": 1,
                "resource_id": "1",
                "right_create": 1,
                "right_delete": 1,
                "right_read": 1
            }, {
                "right_update": 1,
                "resource_id": "2",
                "right_create": 1,
                "right_delete": 1,
                "right_read": 1
            }, {
                "right_update": 1,
                "resource_id": "3",
                "right_create": 1,
                "right_delete": 1,
                "right_read": 1
            }]
        } : state.user
        return user;
    }
    
}

`

12月3日提问
2 个回答
0

我觉得你压根没必要把一个单独的函数(mackAccessId)放在actions,vuex单项数据流完整流程是在actions异步函数派发到mutations,再去更新state。所以我建议直接把这个函数写在外面,state接收函数返回值。

0

用action来提交mutation进而改变state的数据吧

mutations: {
  ...
  setAccessId (state, text) {
    state.makeAccessId = text
  }
}

actions: {
  makeAccessId: ({ commit }) => {
    var text = "";
    var possible = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 9; i++ )
    text += possible.charAt(Math.floor(Math.random() * possible.length));

    <!-- action提交mutation来改变 -->
    commit('setAccessId', text)
  }

}

撰写答案

推广链接