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