简体   繁体   中英

what is the difference with Array.prototype.splice and arr.splice in vuejs?

code:(vue2.0, vue-router)

<template>
 <a v-for="apiItem in allApis" href="#"></a>
</template>
<script>
  computed: mapGetters([
    'allApis'
  ]),
</script>

and in store/modules

const mutations {
  myMutation(state) {
    state.apis.splice(0, 1) // A
    //Array.prototype.splice.call(state.apis, 0, 1); //B
  }
}
const getter = {
  allApis: (state) => {
    return state.apis
  }
}
export default {
  state,
  getters,
  actions,
  mutations
}

the line A will change the allApis and update the view

but the line B will not change the allApi and update the view;

Yes, state.apis.splice(0, 1) will work, as Vue intercept mutating methods and emit events as you can see here in the code .

const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
/**
 * Intercept mutating methods and emit events
 */
;[
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]
.forEach(function (method) {
  // cache original method
  const original = arrayProto[method]

As you see in the source code: arrayMethods are original Array prototype methods which are being overwritten to give you reactivity functionality of vue, so using Array.prototype misses the behavior vue defines.

From the documentation :

Vue wraps an observed array's mutation methods so they will also trigger view updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM