在 vue 模板中使用全局变量 [英] Use global variable in vue template

查看:39
本文介绍了在 vue 模板中使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 vue 模板中使用全局变量.我试图使用它而不在数据字段中设置它,因为它们实际上是一些全局常量.

I'm trying to use a global variable in my vue template. I'm trying to use it without setting it in the data fields, because they're actually some global constants.

<template v-if="item.WheelDrive === WHEEL_DRIVE.ALLROAD">

这会给我属性或方法未在实例上定义但在渲染期间引用"错误.

this will give me the "Property or method is not defined on the instance but referenced during render" error.

是否可以让 vue 不尝试在这里绑定 WHEEL_DRIVE?

Is it possible to direct vue not to try and bind WHEEL_DRIVE here?

推荐答案

就我而言这是不可能的,因为:

每当你在 vue 中使用模板时,你也在以一种或另一种方式使用 vue 模板编译器.所有的模板表达式都会变成render函数,模板编译器生成的源码是这样的:

Whenever you are using templates in vue you are also using vue template compiler in one way or another. All template expressions will be turned into render functions, and the source code that the template compiler generates looks like this:

with(this){return _c('div',[_m(0),(message)?_c('p',[_v(_s(message))]):_c('p',[_v("No message.")])])}

注意开头的 with(this) 语句.因此,将始终在实例上访问其余函数中的每个引用.

Note the with(this) statement at the beginning. Every reference in the remaining function will therefore always be accessed on the instance.

然而,即使有可能,这也是一种反模式:

Vue 在状态管理方面是比较固执的.即使你在这里处理一个常量,vue 仍然鼓励你使用 vuex 在 vue 实例之间共享全局状态.

Vue is relatively opiniated when it comes to state management. Even though you are dealing with a constant here, vue still encourages you to share global state between vue instances using vuex.

您也可以将您的常量反映在您的 vue 实例中,作为您组件数据的一个属性 - 但如果您的应用变得更大,我确实鼓励您使用 vuex.

You could also just reflect your constant in your vue instance as a an attribute of your components data - I do encourage you to use vuex though if your app grows bigger.

这篇关于在 vue 模板中使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆