使用Vue.prototype在vue中注册和使用全局变量

  • 在main.js中添加一个变量到Vue.prototype

    Vue.prototype.$appName = 'My App'

  • 这样 $appName 就在所有的 Vue 实例中可用了,甚至在实例被创建之前就可以

new Vue({
  beforeCreate: function () {
    console.log(this.$appName)
  }
})
  • 每个组件都是一个vue实例,Vue.prototype加一个变量,只是给每个组件加了一个属性,这个属性的值并不具有全局性,比如以下例子:

    main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false
Vue.prototype.$appName = 'main'

/* eslint-disable no-new */
new Vue({
    el: '#app',
    store,
    router,
    components: { App },
    template: '<App/>',

})

给所有组件注册了一个属性$appName,赋予初始值'main',所有组件都可以用它this.$appName访问此变量,如果组件中没有赋值,初始值都是'main'

Test1.vue

<template>
    <div>
         <div @click="changeName">change name</div>
         <div @click="gotoTest2">goto test2</div>
    </div>
</template>
<script>
export default {
    methods:{
        changeName(){
            this.$appName = "test1"
        },
        gotoTest2(){
            this.$router.push({name:"Test2"})
        } 
    },
}
</script>


Test2.vue

<template>
    <div>
         <div>{{this.$appName}} in test2</div>
    </div>
</template>

点击Test1中的change name 再跳转Test2,Test2里面还是显示main in test2

如果要实现全局变量的功能,需要把属性变为引用类型

把Vue.prototype.$appName = 'main'改为Vue.prototype.$appName = { name: 'main' }

后面使用Vue.prototype.$appName.name改变和引用相应的值

这进入Test2后显示test1 in test2

  • 添加的变量名一般以$打头,以区分各个组件自己的成员变量