vue : 在vuex里写一个数组首尾元素互换的方法

不着急上代码,先想几个问题。

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')

以上。




原文地址:https://www.cnblogs.com/foxcharon/p/10152632.html