Javascript 如何在 vue 模板中使用 const?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42662144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How could I use const in vue template?
提问by litbear
I tried to defined a const in a *.vuefile
我试图在*.vue文件中定义一个常量
<script>
export const CREATE_ACTION = 1
export const UPDATE_ACTION = 2
<script>
and use them in template
并在模板中使用它们
<template>
...
<select :disabled="mode === UPDATE_ACTION">
....
</template>
but it seems not work. So, how could I use const in vue template?
但它似乎不起作用。那么,如何在 vue 模板中使用 const 呢?
回答by Bert
Expose them on your data.
将它们暴露在您的数据上。
new Vue({
...
data:{
CREATE_ACTION: CREATE_ACTION
UPDATE_ACTION: UPDATE_ACTION
}
...
})
回答by Saurabh
You can use pluginfor this purpose as you want to include this in multiple components:
您可以为此目的使用插件,因为您想将其包含在多个组件中:
// constsPlugin.js
const YOUR_CONSTS = {
CREATE_ACTION: 1,
UPDATE_ACTION: 2
...
}
YourConsts.install = function (Vue, options) {
Vue.prototype.$getConst = (key) => {
return YOUR_CONSTS[key]
}
}
export default YourConsts
in main.jsor where you define new Vue(), you have to use it like this:
在main.js或你定义的地方new Vue(),你必须像这样使用它:
import YourConsts from 'path/to/plugin'
Vue.use(YourConsts)
Now you can use this in a component template like following:
现在您可以在组件模板中使用它,如下所示:
<div>
<select :disabled="mode === $getConst('UPDATE_ACTION')">
</div>
回答by L. Palaiokostas
If you expose them on your data, you are making them unnecessary reactive, as @mix3d mentioned...
如果你将它们暴露在你的数据上,你就会使它们变得不必要的反应性,正如@mix3d 提到的那样......
A better approach is to add them into Vue object Reactivity in Depth:
更好的方法是将它们添加到 Vue 对象Reactivity in Depth 中:
<template>
<div v-if="action === CREATE_ACTION">Something</div>
</template>
<script>
export default {
created() {
this.CREATE_ACTION = CREATE_ACTION;
this.UPDATE_ACTION = UPDATE_ACTION;
}
})
</script>
回答by MiCc83
What about using Mixins? This is the way I do it. Not sure it is the best or recommended way but the code looks so much cleaner.
使用 Mixin 怎么样?这就是我这样做的方式。不确定这是最好的还是推荐的方式,但代码看起来更干净。
data/actions.js
数据/actions.js
export const CREATE_ACTION = 1;
export const UPDATE_ACTION = 2;
export const actionsMixin = {
data() {
return {
CREATE_ACTION,
UPDATE_ACTION
}
}
}
MyComponent.vue
我的组件.vue
<template>
<div v-if="action === CREATE_ACTION">Something</div>
</template>
<script>
import {actionsMixin, CREATE_ACTION} from './data/actions.js';
export default {
mixins: [actionsMixin]
data() {
return {
action: CREATE_ACTION
}
}
}
</script>

