1:(获取state的方法一)
1-1:这是在state.js文件下定义的。
//根状态 const state = { appName: 'admin', stateValue: 'abc' } export default state在state.js文件定义的属于根状态,可以全局访问使用 this.$store.state.appName
1-2:在模块下的状态如何获取和使用
这时候要使用 this.$store.state.user.userName 来获取 意思就是获取store的state下模块名下(user)的状态名(userName)
2:(获取state的状态方法二)
import { mapState } from 'vuex' //相当于以下写法 //import vuex from 'vuex //const mapState = vuex.mapState computed: { //利用...展开操作符,相当于引入 //状态数组形式用法 ...mapState({ appName }) //状态对象用法 ...mapState({ appName: state => state.appName, userName: state => state.user.userName,//模块下的状态 }), } //对于模块下的状态我们还可以使用定义模块名的方式来使用(这是模块增加了命名空间的时候使用) ...mapState('user',{ userName:state=>state.userName })3:getter的使用(类似与计算computed)
import {mapGetters } from 'vuex' appNameWithVersion () { return this.$store.getters.appNameWithVersion },模块下的getters可以直接使用(除了命名空间下的)
4:mutations的使用(只能作同步操作)
methods: { ...mapMutations([ 'SET_USER_NAME', 'SET_APP_NAME', 'SET_STATE_VALUE' ]), changeUserName () { // this.$store.commit({ // type: 'SET_APP_NAME', // appName: 'newAppName' // }) // this.SET_APP_NAME({ // appName: 'newAppName' // }) // this.$store.state.user.userName = 'haha' 错误的方法 this.SET_USER_NAME('vue-cource') }, }5:actions(异步操作)
import { getAppName } from '@/api/app' const actions = { // updateAppName ({ commit }) { // getAppName().then(res => { // const { info: { appName } } = res // commit('SET_APP_NAME', appName) // }).catch(err => { // console.log(err) // }) // } async updateAppName ({ commit }) { try { const { info: { appName } } = await getAppName() commit('SET_APP_NAME', appName) } catch (err) { console.log(err) } } } export default actions ...mapActions([ 'updateAppName' ]),