如何在Vue模板中使用const?

62

我试图在一个*.vue文件中定义一个const

<script>
    export const CREATE_ACTION = 1,
    export const UPDATE_ACTION = 2
<script>

然后在模板中使用它们:

<template>
    ...
    <select :disabled="mode === UPDATE_ACTION">
    ....
</template>

但它不能工作。我如何在Vue模板中使用const

8个回答

71

如果您在数据中公开它们,就会使它们变得不必要地反应迅速,正如@mix3d所提到的那样...

更好的方法是将它们添加到Vue对象深入响应式原理中:

<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>

2
在我看来,这是最合适的答案。将数据暴露出来使它们变得具有响应性,但你仍然需要在模板中使用字符串值,而我们首先要避免这种情况。 - metasync
这个我支持。可以通过编写一个混入工厂来进一步详细说明您的 created 钩子动态生成:function mixinFactory(constants) { return { created() { Object.keys(constants).forEach((cName) => this[cName] = constants[cName]); }, }; } - Tibi Neagu
3
除了似乎无法与 TypeScript 很好地协作之外,我喜欢这种方法。有人能提出一种消除这里 TS 错误的方法吗? - Sean
有没有办法将这些变量变成真正的常量? - Incinerator
1
@Incinerator 您可以将它们作为 frozen object 附加:this.constants = Object.freeze({ ONE: 1, TWO: 2 })。 为了使其起作用,您需要将常量添加到自己的 frozen 对象中,并将其添加到 this 的任意键中,而不是直接添加到 this 中。 - Impirator

43

将它们暴露在您的数据上:

new Vue({
    data:{
        CREATE_ACTION: CREATE_ACTION,
        UPDATE_ACTION: UPDATE_ACTION
    }
})

14
但我希望在另一个组件中使用它,那么...更加优雅一些? - litbear
@litbear,您可以使用mixin或插件在多个组件中包含内容,但要在模板中引用它们,您必须将它们公开在数据上。 - Bert
17
这种方法的缺点是默认情况下,这些值会获得Vue的所有交互性(和相关开销)。虽然不是很好,但在小范围使用时应该还可以。 - mix3d
2
将数据暴露给它们会创建值的可观察副本。您不再实际与常量进行比较。 - Thanasis Ioannidis

18

如果您想在多个组件中使用此功能,可以使用插件

// constsPlugin.js
const YOUR_CONSTS = {
  CREATE_ACTION: 1,
  UPDATE_ACTION: 2
  ...
}

let YourConsts = {}; // As suggested by the comments.

YourConsts.install = function (Vue, options) {
  Vue.prototype.$getConst = (key) => {
    return YOUR_CONSTS[key]
  }
}

export default YourConsts

main.js或者你定义new Vue()的地方,你需要这样使用它:

import YourConsts from 'path/to/plugin'

Vue.use(YourConsts)

现在您可以像下面这样在组件模板中使用它:

<div>
   <select :disabled="mode === $getConst('UPDATE_ACTION')">
</div>

我认为YOUR_CONSTS需要与YourConsts大小写相同,因为我收到了错误消息“_YourConsts未定义_”。(ESLint也抱怨说YourConsts未定义。) - Gino Mempin
@GinoMempin,不是的。这是因为该变量尚未定义。回答OP应该先包含“let YourConsts = {}”行,然后再定义install方法。 - XPD
作者的目标是摆脱神秘的代码行,而你向他提供了这些行。 - user9547708

11

那么使用混合(Mixins)呢?这是我所使用的方式。不确定它是否是最佳或推荐的方式,但代码看起来更加清晰整洁。

data/actions.js

export const CREATE_ACTION = 1;
export const UPDATE_ACTION = 2;

export const actionsMixin = {
  data() {
    return {
      CREATE_ACTION,
      UPDATE_ACTION
    }      
  }
}

MyComponent.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>

5
仍会对不应更改的静态对象产生响应开销。 - mix3d
也许可以在 created() 阶段声明它。 - Kalnode

7
在Vue 3中,您可以使用setup()
示例:
<template>
  <div>
    hello {{ fooConst }}
  </div>
</template>

<script>
const fooConst = "bar";

export default {
  setup() {
    return {
      fooConst,
    }
  },
}
</script>

或者完全使用组合 API:

<script setup>
const fooConst = "bar";
</script>

<template>
  <div>
    hello {{ fooConst }}
  </div>
</template>

7
<template>
  <div v-if="FOO_CONST.bar">Something</div>
</template>

<script>
import {FOO_CONST} from './const.js';

export default {
  data() {
    return {
      FOO_CONST: Object.freeze(FOO_CONST) // this makes vue not reactive this data property
    }      
  }
}
</script>

2
<template>
  <div>
    <p :style="{ color: $options.COLOR }">
      {{$options.HELLO}} {{$options.PERSON}}
    </p>
  </div>
</template>

<script>
const HELLO = 'Hello there.';
const COLOR = 'red';

export default {
  mounted() {
    console.log('Hello world');
  },
  COLOR,
  HELLO,
  PERSON: 'General Kenobi!',
}
</script>

2
我发现Mixins是一种很好的方法,可以将常量非响应式地添加到Vue对象中。
首先创建你的常量:
// Action.js
const Action = {
  CREATE: 1,
  UPDATE: 2
}

Action.Mixin = {
  created () {
    this.Action = Action
  }
}

export default Action

然后在组件中:

<template>
  <select :disabled="mode === Action.UPDATE">
</template>

<script>
import Action from './Action.js'

export default {
  mixins: [Action.Mixin]
}
</script>

这就像是Alessandro Benoit和L. Palaiokostas答案的结合。


你仍然需要在每个组件中进行声明,因此与其他方法相比并没有太多的好处。 - Kalnode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接