Vue組件為什么data必須是一個函數(shù)
前言
我們需要先復(fù)習(xí)下原型鏈的知識,其實這個問題取決于 js ,而并非是 vue 。
function Component(){ this.data = this.data}Component.prototype.data = { name:’jack’, age:22,}
首先我們達成一個共識(沒有這個共識,請補充下 js 原型鏈部分的知識):
實例它們構(gòu)造函數(shù)內(nèi)的this內(nèi)容是不一樣的。 Component.prototype ,這類底下的方法或者值,都是所有實例公用的。解開疑問
基于此,我們來看看這個問題:
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)
此時,componentA 和 componentB data之間指向了同一個內(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)
此時,componentA 和 componentB data之間相互獨立, age 分別是 55 和 22 ,沒有問題!
總結(jié)
自己突然對這個問題懵逼,不過事后想了想還是自己基礎(chǔ)知識忘得太快。以前學(xué)習(xí) js 的時候,最基礎(chǔ)的:構(gòu)造函數(shù)內(nèi)和原型之間的區(qū)別都模糊了。想不到 vue 這個小問題讓我溫故而知新了一次。
到此這篇關(guān)于Vue組件為什么data必須是一個函數(shù)的文章就介紹到這了,更多相關(guān)Vue組件data是函數(shù)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera2. CSS hack用法案例詳解3. 讀大數(shù)據(jù)量的XML文件的讀取問題4. HTML DOM setInterval和clearInterval方法案例詳解5. XML入門的常見問題(一)6. html小技巧之td,div標(biāo)簽里內(nèi)容不換行7. 詳解盒子端CSS動畫性能提升8. 詳解瀏覽器的緩存機制9. 告別AJAX實現(xiàn)無刷新提交表單10. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法
