Vue 定义全局变量

6,347 阅读1分钟

方法1. 设置并引入全局变量文件

创建一个 Store.vue 文件并暴露出去, 用来保存全局变量

<script>
const name = 'shenxianhui';
const age = 24;

export default {
    name,
    age
};
</script>

在 Test.vue 组件中使用

<template>
    <div>{{ myName }}</div>
    <div>{{ myAge }}</div>
</template>

<script>
import myStore from '@/components/Store'; // 引用模块

export default {
    data () {
        return {
            myName: myStore.name,
            myAge: myStore.age
        }
    }
}
</script>

方法2. 将上面的 Store.vue 文件挂载到 Vue.prototype

main.js

import myStore from '@/components/Store';

Vue.prototype.$myStore = myStore; // 挂载到 Vue 实例上

现在就可以在组件中通过 this.$myStore.name 直接调用了, 不需要再单独引入模块

方法3. 使用 Vuex 来保存变量

这里不做详述, 想了解的朋友可以看下 十分钟入门Vuex