-
在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
- 添加的變量名一般以$打頭,以區分各個組件自己的成員變量
