Vue組件為什么data必須是一個函數
前言
我們需要先復習下原型鏈的知識,其實這個問題取決于 js ,而并非是 vue 。
function Component(){ this.data = this.data}Component.prototype.data = { name:’jack’, age:22,}
首先我們達成一個共識(沒有這個共識,請補充下 js 原型鏈部分的知識):
實例它們構造函數內的this內容是不一樣的。 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之間指向了同一個內存地址,age 都變成了 55, 導致了問題!
接下來很好解釋為什么 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 ,沒有問題!
總結
自己突然對這個問題懵逼,不過事后想了想還是自己基礎知識忘得太快。以前學習 js 的時候,最基礎的:構造函數內和原型之間的區別都模糊了。想不到 vue 這個小問題讓我溫故而知新了一次。
到此這篇關于Vue組件為什么data必須是一個函數的文章就介紹到這了,更多相關Vue組件data是函數內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: