vuex创建全局变量
时间: 2023-12-23 22:28:02 浏览: 99
在Vue.js中,可以使用Vuex来创建全局变量。下面是一个简单的演示:
1. 首先,安装Vuex:
```shell
npm install vuex
```
2. 在你的Vue项目中,创建一个store.js文件,并在其中定义全局变量:
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
globalVariable: 'Hello, Vuex!'
},
mutations: {
updateGlobalVariable(state, newValue) {
state.globalVariable = newValue
}
}
})
export default store
```
3. 在你的main.js文件中引入store.js,并将其挂载到Vue实例上:
```javascript
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
```
4. 现在,你可以在任何组件中使用全局变量了。例如,在一个组件中获取和更新全局变量的值:
```javascript
<template>
<div>
<p>{{ globalVariable }}</p>
<button @click="updateVariable">Update Variable</button>
</div>
</template>
<script>
export default {
computed: {
globalVariable() {
return this.$store.state.globalVariable
}
},
methods: {
updateVariable() {
this.$store.commit('updateGlobalVariable', 'New Value')
}
}
}
</script>
```
这样,你就成功地使用Vuex创建了一个全局变量。
阅读全文
相关推荐

















