Vue组件的date需是函数为什么,如何用代码说明
在日常操作或是项目的实际应用中,有不少朋友对于“Vue组件的date需是函数为什么,如何用代码说明”的问题会存在疑惑,下面小编给大家整理和分享了相关知识和资料,易于大家学习和理解,有需要的朋友可以借鉴参考,下面我们一起来了解一下吧。
现在大家对于Vue组件的date需是函数为什么,如何用代码说明的内容应该都有一定的认识了吧,希望这篇能对大家有所帮助。最后,想要了解更多,欢迎关注博信,博信将为大家推送更多相关的文章。
前言
我们需要先复习下原型链的知识,其实这个问题取决于 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 ,没有问题!
总结
现在大家对于Vue组件的date需是函数为什么,如何用代码说明的内容应该都有一定的认识了吧,希望这篇能对大家有所帮助。最后,想要了解更多,欢迎关注博信,博信将为大家推送更多相关的文章。
版权声明
本文仅代表作者观点,不代表博信信息网立场。