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

2020-05-25  本文已影响0人  studentliubo
<template>
 <div class="hello">
   <h1>{{ msg }}</h1>
   <h3>Constant number : {{ numberOne }}</h3>
 </div>
</template>
...
data () {
   this.numberOne = NumberOne;
}

这种方式是将常量绑定到data上,因data上的属性会在component创建的时候自动被监听,在性能上不太友好,故不推荐。

created () {
    this.NUMBER_ONE = NumberOne;
}
...
<h3>Constant number : {{ NUMBER_ONE }}</h3>

该方法在性能上要优于上面的,这是因为在component执行钩子函数时,数据的监听函数已经执行完成,这个时候使用变量也就有效的避免了资源的浪费,

Note: component的自有属性都是以$或_开始的,只要你定义的变量不是以这种为前缀的都没问题

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>

当你有很多常量需要使用,而且好多地方都需要的时候,这种方式比较合适,

上一篇 下一篇

猜你喜欢

热点阅读