vuex仿splice实现对一个数组的增删改
<h3>Z.splice(array, options)</h3>
<pre><code class="language-javascript">// 加强的splice,对原数组的增删改, 主要用于vuex
const splice = function (array, d) {
if (!Array.isArray(array)) {
console.error('期待一个数组')
return array
}
// #1 解构d数组并添加到array尾部 d = [item1, item2]
if (Array.isArray(d)) {
return array.splice(array.length, 0, ...d)
}
const index = Number.isInteger(d.index) ? d.index : 0
const howmany = Number.isInteger(d.howmany) ? d.howmany : 1 //缺省值为1
if (!d.items) {
// #2 删除1项 d = { index: Number }
return array.splice(index, howmany)
} else {
// #3 增删改 d = { index: Number, howmay: Number, items: arrayObject }
const items = Array.isArray(d.items) ? d.items : [d.items]
return array.splice(index, howmany, ...items)
}
}</code></pre>
<pre><code class="language-plantuml">skinparam backgroundColor #FCFCFC
!includeurl https://raw.githubusercontent.com/xuanye/plantuml-style-c4/master/core.puml
GREEN_ARROW
@startuml
start
:Z.splice(array,options);
if (Array.isArray(options) ?) then (Y)
:解构并添加到数组末尾;
else (N)
:options = {
index: index,
howmany: 1,
items: items
};
split
:index
规定添加/删除项目的位置。默认0;
split again
:howmany
要删除的项目数量。如果设置为 0,则不会删除项目。默认1;
split again
:items
向数组添加的新项目。;
if (Array.isArray(items) ?) then (Y)
:解构;
endif
:追加到数组的指定位置;
end split
endif
stop
@enduml</code></pre>
<h3>vuex文件</h3>
<pre><code class="language-javascript">import Z from '@/lib/Z'
export default {
state: {
list: []
},
mutations: {
Z.splice(state.list, options)
}
}</code></pre>
<h3>组件中使用</h3>
<h5>添加n个</h5>
<pre><code class="language-javascript">const { commit } = this.$store
const array = [item1, item2, item3]
commit('splice', array) // array必须是数组,将被解构追加到末尾</code></pre>
<h5>删除某项</h5>
<pre><code class="language-javascript">const { commit } = this.$store
const options = {
index: index
}
commit('splice', options)</code></pre>
<h5>更新某项</h5>
<pre><code class="language-javascript">const { commit } = this.$store
const options = {
index:0,
// howmany: 1, // 删除的个数,缺失值为 1
items: arrayObject // 追加的数据,数组将被解构为多个
}
commit('splice', options)</code></pre>