es6中的[]()是怎样的用法

看别人的代码时候,无意间看到[](){}这样的用法,但阅尽百度都没看到这个方法的详解,所以想咨询一下大家。
具体是在vuex里的store.js看到

[changeListStatus](state,bool){ state.isAllList = bool; }

const mutations = {  
    [changeListStatus](state,bool){  
        state.isAllList = bool;  
    },  
    [addNote](state) {  
        const newNote = {  
            text: 'New note',  
            favorite: !state.isAllList,  
            _rm: Math.random(),  
        }  
        state.notes.push(newNote);  
        state.activeNote = newNote;  
    },  
    [editNote](state, text) {  
        state.activeNote.text = text;  
    },  
    [deleteNote](state){  
        let rm = state.activeNote['_rm'];  
        let index = state.notes.findIndex(function(v,i){  
            if( rm == v['_rm'] ) return true;  
            return false;  
        });  
        if(index >= 0) state.notes.splice(index, 1);  
        state.activeNote = state.notes[0] || {};  
    },  
    [toggleFavorite](state){  
        state.activeNote['favorite'] = !state.activeNote['favorite']  
    },  
    [setActiveNote](state,note){  
        state.activeNote = note;  
    },  
}  
阅读 2.4k
2 个回答

问题分解

var changeListStatus='foo';
var obj={
    [changeListStatus](state,bool){ state.isAllList = bool; }
}

=>

var changeListStatus='foo';
var obj={
    [changeListStatus]:function(state,bool){ state.isAllList = bool; }
}

=>

var obj={
    foo:function(state,bool){ state.isAllList = bool; }
}

[]表示属性内是可计算的,常见的是比如 给对象安装迭代器

var obj={}
obj[Symbol.iterator]=function(){}

Computed Property Names
Method Properties
这两个语法一起用就是这样了

const methodName = "aaa";

const v = {
    [methodName](bar) {
        console.log("bar=", bar);
    }
};

v.aaa("BBBar"); // bar = BBBar
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题