vue 数据 函数过滤_Vue,为什么数据必须是函数

vue 数据 函数过滤

Using Vue you might surely asked yourself the question “why must data be a function that returns an object, and not just an object?”

使用Vue,您肯定会问自己一个问题:“为什么data必须是返回对象的函数,而不仅仅是返回对象?”

<template>
  <a v-on:click="counter = counter + 1">{{counter}}</a>
</template>

<script>
export default {
  data: function() {
    return {
      counter: 0
    }
  }
}
</script>

Especially considering that in some places, data is not a function, as you most probably see in the App component in several examples.

特别是考虑到在某些地方, data 不是功能,正如您在几个示例中的App组件中最有可能看到的那样。

The explanation is that when the component is used multiple times, if it’s not a function, but a regular object, like this:

解释是,如果多次使用该组件,则它不是函数,而是常规对象,例如:

data: {
  counter: 0
}

then because of how JavaScript works, every single instance of the component will share this property.

然后由于JavaScript的工作原理, 该组件的每个实例都将共享此属性

This is not what you want in 99.9% of the cases, and instead you must do:

在99.9%的情况下,这不是您想要的,而是必须执行以下操作:

data: function() {
  return {
    counter: 0
  }
}

It might be non-intuitive at first, but once you accept this explanation and learn that it’s kind of harmful to your application, and a possible source of bugs, you’ll remember to always use a function for data.

乍一看可能不是很直观,但是一旦您接受了这种解释并得知它对您的应用程序有害,并且可能是错误的源头,您将记住始终使用函数来处理数据。

翻译自: https://flaviocopes.com/vue-data-function/

vue 数据 函数过滤

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值