在Vue的template中使用常量的三種方式

  • 如果我們直接在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)你有很多常量需要使用,而且好多地方都需要的時候,這種方式比較合適,

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容