vuex在项目中的应用

317 阅读1分钟

1、理解各个模块在vuex中功能含义

state -- 状态对象

getter -- 基于state的计算属性 -- 可保存state中变化的属性

mutation -- 直接更新state的方法 mutation-type -- mutation的type名称常量

action -- 通过mutation更新state的方法 -- 在此调用api接口

2、熟悉vuex的api,熟练各个功能调用方法

vuex.vuejs.org/zh/guide/st…

直接更改state的方法

this.$store.state.address= this.topBoxList

通过action更改state状态方法

this.$store.dispatch('getAddress')
...mapActions(['getAddress', 'getUserInfo'])

获取state状态方法

this.$store.state.address
...mapState(['address', 'categorys', 'userInfo']),

获取state的计算属性方法

this.$store.getters.totalCount
...mapGetters(['totalCount', 'totalPrice']),

3、基础用法 — 示例代码

安装、引入

npm install vuex

**main.js**

import store from './store/index'

export default new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

index . js

/*vuex最核心的管理对象store */
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'

Vue.use(Vuex)

export default new Vuex.Store({  
state,  
mutations,  
actions,  
getters})

state . js

/*状态对象 */
export default {  
latitude: 40.10038, // 纬度  
longitude: 116.36867, // 经度  
address: {}, //地址相关信息对象}

getter . js

/*包含多个基于state的getter计算属性的对象 */
export default {
    totalCount (state) {
        return state*20
    },
}

mutation-type . js

/*包含n个mutation的type名称常量 */
export const RECEIVE_ADDRESS = 'receive_address' // 接收地址

mutation . js

/*直接更新state的多个方法的对象 */
import Vue from 'vue'import {  RECEIVE_ADDRESS,} from './mutation-types'

export default {  
    [RECEIVE_ADDRESS] (state, {address}) {    
    state.address = address  
    }
}

action . js

/*通过mutation间接更新state的多个方法的对象 */
import {  RECEIVE_ADDRESS,} from './mutation-types'
import {  reqAddress,} from '../api'

export default {  // 异步获取地址  
    async getAddress({commit, state}) {    // 发送异步ajax请求    
        const geohash = state.latitude + ',' + state.longitude    
        const result = await reqAddress(geohash)    
        // 提交一个mutation    
        if (result.code === 0) {      
            const address = result.data      
            commit(RECEIVE_ADDRESS, {address})    
        }  
    }
}

单页面引用

<script>  
import {mapActions,mapState, mapGetters} from 'vuex'  

export default {    
    mounted () {      
        // this.$store.dispatch('getAddress') 
        this.$store.state.address= '测试数据'
        this.getAddress()      
        this.getUserInfo()    
        
    },    
    methods: {      
        ...mapActions(['getAddress', 'getUserInfo'])    
        
    },
        
    computed: {      
        ...mapState(['cartFoods', 'info']),      
        ...mapGetters(['totalCount', 'totalPrice']),
    }  
}
</script>
    ```