• 19.vue组件中data为什么必须是一个函数


    https://www.jb51.net/article/188491.htm

    前言

    我们需要先复习下原型链的知识,其实这个问题取决于 js ,而并非是 vue 。

    1
    2
    3
    4
    5
    6
    7
    function Component(){
     this.data = this.data
    }
    Component.prototype.data = {
      name:'jack',
      age:22,
    }

    首先我们达成一个共识(没有这个共识,请补充下 js 原型链部分的知识):

    • 实例它们构造函数内的this内容是不一样的。
    • Component.prototype ,这类底下的方法或者值,都是所有实例公用的。

    解开疑问

    基于此,我们来看看这个问题:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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 了:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    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 ,没有问题!

  • 相关阅读:
    Google API 详解
    Why should I use SASS?
    Google Maps and ASP.NET
    IP摄像机
    解决母版页报错“内容控件必须是内容页中的顶级控件,或是引用母版页的嵌套母版页。”
    sass服务
    C#中操作符的重载(Time类)
    第一次面试
    单链表(C++)
    指针和引用的区别(C++)
  • 原文地址:https://www.cnblogs.com/dream111/p/13499064.html
Copyright © 2020-2023  润新知