Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vuex 操作数组 #20

Open
huangshuwei opened this issue Nov 8, 2018 · 2 comments
Open

vuex 操作数组 #20

huangshuwei opened this issue Nov 8, 2018 · 2 comments
Labels

Comments

@huangshuwei
Copy link
Owner

huangshuwei commented Nov 8, 2018

前言

项目中使用状态管理器操作数组是很频繁的,找到最优的方案会让操作数组更便捷高效

新增数组某项

简单的往数组中新增。使用 push 插入

...
  state: {
             arr: [
                {name: 'a', id: 0}
            ]
        },
   mutations: {

       addArrayItem(state, {arrItem}) {

           state.arr.push(arrItem)
        }
   }
...

往数组中指定位置插入。使用 splice

...
  state: {
             arr: [
                {name: 'a', id: 0}
            ]
        },
   mutations: {

       addArrayItem(state, {index, arrItem}) {

             state.arr.splice(index, 0, arrItem)
       }
   }
...

修改数组某项

修改数组的某一项,splice 方案

...
  state: {
             arr: [
                {name: 'a', id: 0}
            ]
        },
   mutations: {

       updateArrayItem(state, {arrItem}) {

                const index = state.arr.findIndex(item => item.id === arrItem.id);
                state.arr.splice(index,1,arrItem)
          }
   }
...

修改数组的某一项,Vue.set 方案

...
  state: {
             arr: [
                {name: 'a', id: 0}
            ]
        },
   mutations: {

       updateArrayItem(state, {arrItem}) {

                const index = state.arr.findIndex(item => item.id === arrItem.id);
                Vue.set(state.arr, index, arrItem);
          }
   }
...

修改数组的某一项,Object.assign 方案

...
  state: {
             arr: [
                {name: 'a', id: 0}
            ]
        },
   mutations: {

       updateArrayItem(state, {arrItem}) {

                const item = state.arr.find(item=> item.id === arrItem.id);
                Object.assign(item, arrItem);
          }
   }
...

删除数组某项

删除数组的某一项,使用splice

...
  state: {
             arr: [
                {name: 'a', id: 0}
            ]
        },
   mutations: {

       removeArrayItem(state, {arrItem}) {

                const index = state.arr.findIndex(item => item.id === arrItem.id);
                state.arr.splice(index, 1)
          }
   }
...

未完,待续...

@huangshuwei huangshuwei added the vue label Nov 8, 2018
@huangshuwei huangshuwei changed the title vuex 数组操作 vuex 操作数组 Nov 8, 2018
@TheProudSoul
Copy link

删除数组某项 应该是 findIndex,写成 find 了

@huangshuwei
Copy link
Owner Author

删除数组某项 应该是 findIndex,写成 find 了

是的,谢谢反馈

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants