vuex与axios结合使用

在vue项目中,组件间相互传值、后台获取的数据需要供多个组件使用的情况,有必要考虑引入vuex来管理这些凌乱的状态。

首先新需要在项目中安装vuex:

命令行 npm install vuex    - - save  - dev

在项目的入口 js 文件 main.js 中引入

import store from './store';

并将 store 挂载到 vue 上

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');

创建store目录结构(根据需求繁或简)

store下index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import userStore from './userInfo/'

const store = new Vuex.Store({
  modules: {
  	userStore,
  }
})

export default store

 

userInfo下index.js

import axios from 'axios'
const userStore = {
    state: {
		user: {
			name: '',
		}
    },
    getters: {},
    mutations: {
        setUser(state, payload){
            state.user.name = payload
        },
    },
    actions: {
    	getName({commit}){
             axios.get(url, params)
                .then(response => {
                    commit("setUser",res.name);
                })
                .catch((error) => {
                    console.log(error)
                })
	    }
    },
    //plugins: [createPersistedState()]
}

export default userStore

使用vuex的组件中进行分发

mounted () { this.$store.dispatch('getName') },
//created或者mounted周期都可以

需要取回 state 的组件中使用 mapState 获取 state:

import { mapState } from 'vuex';

export default {
  ...
  computed: {
    ...mapState([
       name: state => state.userStore.user.name
    ])
  },
  ...      
}

 

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值