
通过 vue cli 定义和使用全局变量
在使用 Vue CLI 创建项目后,可以定义一个全局变量并将其用于 Vue 组件。具体步骤如下:
1. 定义全局变量
以 test2.js 为文件名创建脚本文件,并将以下代码复制到其中:
/*globals abc_test:true*/
abc_test = {
a1() {
alert("12");
},
};2. 配置 Vue CLI
立即学习“前端免费学习笔记(深入)”;
在 vue.config.js 文件中,添加以下配置:
module.exports = {
assetsDir: 'static',
};这将指定静态资源应位于 static 目录中。
3. 引入全局变量
在 index.html 文件中,在 <head> 标签内引入 test.js 脚本:
<script type="text/javascript" src="/static/js/test.js"></script>
4. 在 Vue 组件中使用全局变量
在 Vue 组件中,例如 Test.vue,从 /static/js/test.js 导入所需的模块,然后使用全局变量:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
{{ text }}
<button @click="test()">aaa</button>
</div>
</template>
<script>
import { tb } from '/static/js/test.js';
export default {
name: 'Test',
props: {
msg: String,
},
data() {
return {
text: "哈哈哈",
};
},
methods: {
test() {
tb.abc_test.a1();
},
},
};
</script>以上就是如何使用 Vue CLI 在 Vue 组件中定义和使用全局变量?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号