- 如果我們直接在template標(biāo)簽中使用常量的話會得到下面的錯誤信息:
[Vue warn]: Property or method “NumberOne” is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
-
方式一: 添加到data()
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h3>Constant number : {{ numberOne }}</h3>
</div>
</template>
...
data () {
this.numberOne = NumberOne;
}
這種方式是將常量綁定到data上,因data上的屬性會在component創(chuàng)建的時候自動被監(jiān)聽,在性能上不太友好,故不推薦。
-
方式二: 在鉤子函數(shù)created中定義一個變量
created () {
this.NUMBER_ONE = NumberOne;
}
...
<h3>Constant number : {{ NUMBER_ONE }}</h3>
該方法在性能上要優(yōu)于上面的,這是因為在component執(zhí)行鉤子函數(shù)時,數(shù)據(jù)的監(jiān)聽函數(shù)已經(jīng)執(zhí)行完成,這個時候使用變量也就有效的避免了資源的浪費,
Note: component的自有屬性都是以$或_開始的,只要你定義的變量不是以這種為前綴的都沒問題
-
方式三:使用plugin插件
const Numbers = {
NumberOne: 1
};
Numbers.install = function (Vue) {
Vue.prototype.$getConst = (key) => {
return Numbers[key];
}
};
export default Numbers;
// 在main.js添加如下代碼
import constPlugin from "./components/constPlugin";
Vue.use(constPlugin);
// 使用
<h3>Constant number : {{ $getConst('NumberOne') }}</h3>
當(dāng)你有很多常量需要使用,而且好多地方都需要的時候,這種方式比較合適,