簡體   English   中英

vuejs 中的 Array.prototype.splice 和 arr.splice 有什么區別?

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

代碼:(vue2.0,vue-router)

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

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
}

line A行將更改allApis並更新視圖

但是line B不會更改allApi並更新視圖;

是的, state.apis.splice(0, 1)會起作用,因為 Vue 會攔截變異方法並發出事件,正如您在代碼中看到的那樣。

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]

正如您在源代碼中看到的: arrayMethods是原始的 Array 原型方法,它們被覆蓋以提供 vue 的反應性功能,因此使用Array.prototype會錯過 vue 定義的行為。

文檔中:

Vue 包裝了觀察到的數組的變異方法,因此它們也會觸發視圖更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM