1. 安装vuex
// 用的是vue2的话
npm i vuex@3
// 用的是vue3的话
npm i vuex 或者 npm i vuex@4
2. store里配置vuex
模块化配置modules
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import login from './modules/login'
Vue.use(Vuex)
export default new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {},
modules: {
login
}
})
配置单独模块的文件
// store/modules/login.js
export default {
namespaced: true, // 开启命名空间,避免冲突
state: {
name: 'jay'
},
getters: {},
mutations: {},
actions: {}
}
3. main.js挂载vuex
import Vue from 'vue'
import App from './App.vue'
import router from '@/router'
import VueRouter from 'vue-router'
+ import store from './store'
Vue.use(VueRouter)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router,
+ store
}).$mount('#app')
4. 页面里使用vuex里的数据
<template>
<div>
<h1>我是登录页</h1>
vue里的数据是:{{ $store.state.login.name }}
</div>
</template>
<script>
export default {
name: 'V2TemplateLogin',
data () {
return {}
},
mounted () {},
methods: {}
}
</script>
<style lang="scss" scoped>
</style>
5. map简化数据的访问
mapState和mapGetters(属性)都写在computed里面
mapMutations和mapActions(方法)写在methods里面
<template>
<div>
<h1>我是登录页</h1>
{{name}}
</div>
</template>
import { mapState } from 'vuex'
computed: {
...mapState('login', ['name'])
}