为什么 vue 组件数据必须是函数? [英] Why must vue component data be a function?

查看:39
本文介绍了为什么 vue 组件数据必须是函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Vue 组件,并找到他们对为什么需要数据的解释成为一个有点令人困惑的函数:

I am reading up on Vue components, and find their explanation of why data needs to be a function somewhat confusing:

根实例

var vm = new Vue({
  el: '#example',
  data: {
    message: 'here data is a property'
  }
})

一个组件

var vm = new Vue({
  el: '#example',
  data: function () {
     return {
       counter: 0
     }
  }
})

Vue 文档通过为每个组件分配一个全局计数器变量来解释这种差异,然后他们惊讶地发现每个组件共享相同的数据......他们也没有解释为什么他们已经在这里使用了一个函数.

The Vue docs explain this difference by assigning a global counter variable to each component, and then they act surprised that each component shares that same data... Also they don't explain why they already use a function here.

var data = { counter: 0 }

Vue.component('simple-counter', {
  template: '<div>{{ counter }}</div >',
  data: function () {
    return data  
  }
})

当然现在共享数据

<simple-counter></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>

当您引用全局对象作为数据源时,组件没有自己的数据也就不足为奇了.对于将数据作为属性的根 Vue 实例也是如此.

When you reference a global object as your data source, it's no surprise that the components don't have their own data. That is also true for root Vue instances that have data as a property.

var mydata = { counter: 0 }

var vm1 = new Vue({
  el: '#example1',
  data: mydata
})

var vm2 = new Vue({
  el: '#example2',
  data: mydata
})

所以我仍然有一个问题,为什么组件不能有数据属性?

So I'm still left with the question why a component can't have a data property?

推荐答案

从我的理解来看,是为了节省内存

From my understanding of this, It's to save memory

许多框架,例如 Angular 2 或(有时)React,使组件的每个实例成为一个单独的对象.这意味着每个组件需要的一切都为每个组件初始化.但通常情况下,您实际上只需要在每次初始化时将组件的数据分开.方法等保持不变.

Many frameworks, such as Angular 2 or, (at times) React, make each instance of a component a separate object. This means that everything each component needs is initialized for every component. Normally though, you really only need to keep a component’s data separate for each initialization. Methods and such stay the same.

Vue 通过让数据成为一个返回对象的函数来避免这个陷阱.这允许单独的组件具有单独的内部状态,而无需完全重新实例化整个组件.方法、计算属性定义和生命周期挂钩仅创建和存储一次,并针对组件的每个实例运行.

Vue avoids that pitfall by having data be a function that returns an object. That allows separate components to have separate internal state without needing to fully re-instantiate the entire component. Methods, computed property definitions, and lifecycle hooks are created and stored only once, and run against every instance of a component.

看到这个

这篇关于为什么 vue 组件数据必须是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆