英文:
What's the point of hardcoded class properties in Vue Options API/
问题
Is there a point to defining properties like var_B when using Vue Options API? They are not reachable when defining methods, or inside the template tags. I'm aware I can define variables inside data() for those purposes, but I'm wondering why Vue allows this at all, and if there exists a practical use case
export default {
var_B: 10, // 为什么在这里定义属性?
data() {
return {
var_A: 9,
};
},
methods: {
double() {
this.var_A = this.var_A * var_B;
// 导致 9 x undefined = NaN
},
},
};
<template lang="html">
<div>Variable A: {{ var_A }}</div> <!-- 9 -->
<div>Variable B: {{ var_B }}</div> <!-- undefined -->
<button @click="double">Try to Double var_A</button>
</template>
I attempted to use the hardcoded class properties inside the template tags, and inside a method, neither of which worked.
英文:
Is there a point to defining properties like var_B when using Vue Options API? They are not reachable when defining methods, or inside the template tags. I'm aware I can define variables inside data() for those purposes, but I'm wondering why Vue allows this at all, and if there exists a practical use case
<script>
export default {
var_B: 10, // WHY DEFINE PROPERTIES HERE AT ALL?
data() {
return {
var_A: 9,
};
},
methods: {
double() {
this.var_A = this.var_A * var_B;
// causes 9 x undefined = NaN
},
},
};
</script>
<template lang="">
<div>Variable A: {{ var_A }}</div> <!-- 9 -->
<div>Variable B: {{ var_B }}</div> <!-- undefined -->
<button @click="double">Try to Double var_A</button>
</template>
I attempted to use the hardcoded class properties inside the template tags, and inside a method, neither of which worked
答案1
得分: 1
data()
是一个响应式对象。Vue 会监视它的变化,如果 data()
返回的对象中的任何值发生改变,Vue 会更新所有使用它的地方(computed
、methods
、模板)。
在 Vue 的基本导出中声明自定义属性(在你的示例中的 var_b
)是无效的。应用程序不会报错,但你无法通过 this.
(或模板中)访问在那里定义的内容。
如果你只需要在组件解析时简单地读取常量,而不关心 Vue 是否监视它的变化,请将它放在 <script>
标签的根部:
const b = 10
export default {
data: () => ({
a: 5
}),
computed: {
c() { return this.a * b }
}
}
无论何时你改变 a
,c
都会自动成为 this.a
的当前值乘以 b
。
英文:
data()
is a reactive object. It is being watched by Vue for changes and, should any of the values declared in the object returned by data()
change, Vue will update all places where it is used (computed
, methods
, template).
Declaring custom properties on the base export of a Vue (var_b
in your example) is invalid. The application won't error, but nothing you put there is available under this.
(or in the template).
If you want a simple constant read when the component is parsed and don't care about Vue watching it for changes, place it in the root of the <script>
:
const b = 10
export default {
data: () => ({
a: 5
}),
computed: {
c() { return this.a * b }
}
}
Whenever you change a
, c
will automatically become current value of this.a
* b
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论