不着急上代码, 先想几个问题.
vuex 里怎么写方法?
mutation 里写 vuex 方法, 组件中用 commit 调用.
数组首尾元素怎么互换?
- arr.splice(0, 0, arr[arr.length - 1])
- arr.pop()
怎样让这个方法是可复用的?
组件中 commit 的时候提交想改的数组名字, 并在 vuex 方法中进行检测.
需要检测啥?
1 state 中是否存在这个变量
2 这个变量是不是一个符合要求 (length> 1) 的数组?
怎样检测是否存在这个变量?
Object.keys(state) 遍历 state 变量名, 如果能找到和提交的变量名相同的, 则是合法的.
怎样检测这个变量是否符合要求?
Array.isArray(arr) && arr.length> 1
好了, 可以上代码了.
- vuex mutation:
- swapArrayFirstAndLast(state, name){
- // console.log("name", name)
- // console.log(Object.keys(state))
- const stateNameArr = Object.keys(state)
- for (let x in stateNameArr) {
- // console.log(stateNameArr[x])
- if (stateNameArr[x] === name) {
- if (Array.isArray(state[name]) && state[name].length> 1) {
- // console.log("===bingo===")
- let arr = state[name]
- arr.splice(0, 0, arr[arr.length - 1])
- arr.pop()
- break
- } else {
- return
- }
- }
- }
- }
- component.vue:
- this.$store.commit('swapArrayFirstAndLast', 'aSimpleArray')
以上.
来源: http://www.bubuko.com/infodetail-2891636.html