Vue.js 中的“data:"和“data()"有什么区别? [英] What is difference between 'data:' and 'data()' in Vue.js?

查看:83
本文介绍了Vue.js 中的“data:"和“data()"有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以两种方式使用了数据选项.在第一个片段数据对象中包含一个键值,然而,在第二个数据中是一个函数.个人有没有什么好处.在Vue.js Docs上找不到相关的解释下面是两个代码片段:

I have used data option in two ways. In first snippet data object contains a key value, however, in second data is a function. Is there any benefits of individuals.Not able to find relevant explanations on Vue.js Docs Here are two code snippets:

new Vue({
  el: "#app",
  data: {
      message: 'hello mr. magoo'
    }

});

new Vue({
  el: "#app",
  data() {
    return {
      message: 'hello mr. magoo'
    }
  }
});

两者都给我相同的输出.

Both are giving me the same output.

推荐答案

在考虑您的特定代码示例时,对您问题的评论似乎错过了一个关键点.

It seems as though the comments on your question missed a key point when considering your specific code example.

在根 Vue 实例中,即通过 new Vue({ ... }) 构造,您可以简单地使用 data: { ... } 没有任何问题.问题是当您拥有通过 Vue.component(...) 定义的可重用组件时.在这些情况下,您需要使用 data() {return { ... };}data: function() {return { ... };}.

In a root Vue instance i.e. constructed via new Vue({ ... }), you can simply use data: { ... } without any problems. The issue is when you have reusable components that are defined via Vue.component(...). In these instances, you need to either use data() {return { ... };} or data: function() {return { ... };}.

这样做的原因是为了确保对于可重用子组件的每个单独实例,都有一个包含所有正在操作的数据的唯一对象.如果在子组件中,您改为使用 data: { ... },则子组件之间将共享相同的数据对象,这可能会导致一些令人讨厌的错误.

The reason for this is to ensure that for each individual instance of the reusable child component, there is a unique object containing all of the data being operated on. If, in a child component, you instead use data: { ... }, that same data object will be shared between the child components which can cause some nasty bugs.

请查看 Vue.js 的相应部分文档以获取有关此问题的更多信息.

Please review the corresponding section of the Vue.js documentation for more information regarding this problem.

这篇关于Vue.js 中的“data:"和“data()"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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