久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

瀏覽:136日期: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
相關文章:
主站蜘蛛池模板: 阿克| 郓城县| 桑日县| 会昌县| 泗洪县| 会同县| 镇安县| 云浮市| 扎兰屯市| 金山区| 阆中市| 秭归县| 民和| 菏泽市| 宁河县| 蕲春县| 昌都县| 平陆县| 通州市| 迭部县| 乌拉特后旗| 柞水县| 伊吾县| 宿迁市| 九江县| 什邡市| 微山县| 那坡县| 读书| 峡江县| 济源市| 保康县| 乐安县| 双鸭山市| 城口县| 宝山区| 嵩明县| 剑河县| 龙海市| 响水县| 大英县|