美文网首页
在Vue的template中使用常量的三种方式

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

作者: studentliubo | 来源:发表于2020-05-25 23:37 被阅读0次
  • 如果我们直接在template标签中使用常量的话会得到下面的错误信息:
    [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创建的时候自动被监听,在性能上不太友好,故不推荐。

  • 方式二: 在钩子函数created中定义一个变量

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

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

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>

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

相关文章