Vue組件為什么data必須是一個(gè)函數(shù)
前言
我們需要先復(fù)習(xí)下原型鏈的知識(shí),其實(shí)這個(gè)問題取決于 js ,而并非是 vue 。
function Component(){ this.data = this.data}Component.prototype.data = { name:’jack’, age:22,}
首先我們達(dá)成一個(gè)共識(shí)(沒有這個(gè)共識(shí),請(qǐng)補(bǔ)充下 js 原型鏈部分的知識(shí)):
實(shí)例它們構(gòu)造函數(shù)內(nèi)的this內(nèi)容是不一樣的。 Component.prototype ,這類底下的方法或者值,都是所有實(shí)例公用的。解開疑問
基于此,我們來看看這個(gè)問題:
function Component(){ }Component.prototype.data = { name:’jack’, age:22,}var componentA = new Component();var componentB = new Component();componentA.data.age=55;console.log(componentA,componentB)
此時(shí),componentA 和 componentB data之間指向了同一個(gè)內(nèi)存地址,age 都變成了 55, 導(dǎo)致了問題!
接下來很好解釋為什么 vue 組件需要 function 了:
function Component(){ this.data = this.data()}Component.prototype.data = function (){ return { name:’jack’, age:22,}}var componentA = new Component();var componentB = new Component();componentA.data.age=55;console.log(componentA,componentB)
此時(shí),componentA 和 componentB data之間相互獨(dú)立, age 分別是 55 和 22 ,沒有問題!
總結(jié)
自己突然對(duì)這個(gè)問題懵逼,不過事后想了想還是自己基礎(chǔ)知識(shí)忘得太快。以前學(xué)習(xí) js 的時(shí)候,最基礎(chǔ)的:構(gòu)造函數(shù)內(nèi)和原型之間的區(qū)別都模糊了。想不到 vue 這個(gè)小問題讓我溫故而知新了一次。
到此這篇關(guān)于Vue組件為什么data必須是一個(gè)函數(shù)的文章就介紹到這了,更多相關(guān)Vue組件data是函數(shù)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
