2017-01-06 12 views
2

代碼:(vue2.0,VUE路由器)vuejs中的Array.prototype.splice和arr.splice有什麼區別?

<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並更新視圖;

回答

1

是的,state.apis.splice(0, 1)將起作用,因爲Vue攔截突變方法併發射事件,如您在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] 

當你在源代碼中看到:arrayMethods是原始數組原型方法正被覆蓋給你VUE的反應性官能度,因此,使用Array.prototype射門行爲VUE限定。

documentation

Vue的包裝觀察到的陣列的基因突變的方法,使他們也將觸發視圖更新。

+0

你是對的,但是否意識到,你錯過了一個重要的觀點,在你所指的源代碼中,'export const arrayMethods = Object.create(arrayProto)'正在爲數組創建一個新的原型,所以使用'Array.prototype'會忽略vue定義的行爲。 –

+0

@潘俊傑潘俊傑是的,這就是我在這裏指出的,你得到這些額外的功能,你沒有在'Array.prototype'中得到這些功能,可能我沒那麼清楚,將明確添加它。 – Saurabh