Is there any point in defining properties like var_B when using the Vue Options API? They are not accessible when defining methods or within template tags. I know I can define variables in data() for these purposes, but I'd like to know why Vue allows this and if there are actual use cases
<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 tried using hardcoded class attributes inside template tags and inside methods but neither worked
data()is a reactive object. Vue is monitoring it for changes, and if any of the values declared in the object returned bydata()change, Vue will update everywhere it is used (compute) >,methods,template).Declaring custom properties on Vue's base export (
var_bin the example) Invalid. The application will not error, but anything you put underthis.(or in the template) will not be available.If you wish to read a simple constant when resolving the component and don't care about Vue observing it for changes, place it in the root of
:const b = 10 export default { data: () => ({ a: 5 }), computed: { c() { return this.a * b } } }Whenever you change
a,cautomatically becomes the current value ofthis.a*b.