[英]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.