vuex与axios结合使用 | 您所在的位置:网站首页 › axios使用场景 › 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 storeuserInfo下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 ]) }, ... }
|
CopyRight 2018-2019 实验室设备网 版权所有 |