国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Vue組件為什么data必須是一個函數

瀏覽:154日期:2023-01-13 18:14:13

前言

我們需要先復習下原型鏈的知識,其實這個問題取決于 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是函數內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Vue
相關文章:
主站蜘蛛池模板: 双牌县| 云浮市| 深泽县| 山西省| 密山市| 黄龙县| 吴堡县| 丰城市| 多伦县| 冷水江市| 自治县| 安图县| 阳曲县| 威远县| 上犹县| 土默特右旗| 洪泽县| 原阳县| 合水县| 湘潭县| 广平县| 广汉市| 肃北| 南陵县| 慈利县| 色达县| 扶沟县| 色达县| 开化县| 汤原县| 武汉市| 泸州市| 诸暨市| 彩票| 兰坪| 新化县| 德阳市| 江华| 来安县| 柳江县| 社会|