Vuex--项目全局变量
程序员文章站
2022-03-31 21:17:12
...
需求简介:项目是 vue 项目,需要用到一个全局变量,其他组件都可读取和更新它;使用的 Vuex 解决;
首先 store 文件夹 index.js 通过vuex 五大属性设置好 全局对象或变量
<!-- store-index.js -->
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
user: {},
abnormalOrderTotal:null //异常订单数
},
mutations: {
setAbnormalOrderTotal(state,num){
state.abnormalOrderTotal = num;
}
},
actions: {
handleSetAbnormalOrderTotal(context,num){
context.commit('setAbnormalOrderTotal',num)
}
},
getters:{
getAbnormalOrderTotal(state){
return state.abnormalOrderTotal
}
},
modules: {}
})
然后在项目 main.js 里面引入 store
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import initAxios from './assets/js/axiosPreset'
import './assets/js/element'
import './components/elementConfig'
Vue.config.productionTip = false
new Vue({
router,
store, //这
render: h => h(App),
created() {
initAxios(this)
}
}).$mount('#app')
App.vue里面可以初始化 全局变量的值
<template>
<div id="app">
<page-header></page-header>
<router-view name="login"></router-view>
<router-view></router-view>
</div>
</template>
<script>
import PageHeader from './components/header'
export default {
name: 'App',
components: {
PageHeader
},
mounted() {
let num = Math.floor(Math.random()*100+1)
this.$store.dispatch('handleSetAbnormalOrderTotal',num)
},
methods: {}
}
</script>
<style lang="scss">
@import '/assets/scss/reset';
@import '/assets/scss/config';
#app {
padding-bottom: 50px;
min-width: 1300px;
.page-container {
box-sizing: border-box;
width: 100%;
padding: 76px 20px 0 220px;
.page-content {
box-sizing: border-box;
padding: 20px;
min-height: 600px;
background-color: #fff;
}
}
}
</style>
其他组件调用:
<el-badge :value="getAbnormalOrderTotal" class="item">
<el-radio-button label="2">异常订单</el-radio-button>
</el-badge>
computed: {
getAbnormalOrderTotal() {
return this.$store.getters.getAbnormalOrderTotal
}
},
官方API:vuex
参考文章:VueJS中学习使用Vuex详解