打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
详讲:vue2+vuex+axios
在vue2项目中,组件间相互传值或者后台获取的数据需要供多个组件使用的情况很多的情况下(后台获取数据存入vuex,组件之间共享数据),那么就需要用vuex来管理这些。
整个的流程是在组件的created中提交dispatch,然后通过action调用一个封装好的axios,然后再触发mutation来提交状态改变state中的数据,然后在组件的计算属性中获取state的数据并渲染在页面上
首先新需要在项目中安装vuex:
运行命令:npm install vuex --save-dev
在项目的入口js文件main.js中:import store from './store/index'
并将store挂载到vue上:
  new Vue({    el: '#app',    router,    store,    template: '<App/>',    render: (createElement) => createElement(App)  })
然后看下整个store的目录结构,modules文件夹用来将不同功能也面的状态分成模块,index.js文件夹是store的入口文件,types文件夹是定义常量mutation的。文件夹整个vuex的目录结构如下:
这里我新建了文件夹fetch用来编写所有的axios处理(这里是把axios封装了)并且在fetch文件夹下新建api.js文件:
  import axios from 'axios'  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';  axios.defaults.baseURL = '后台接口公共前缀';  export function fetch(url, params) {      return new Promise((resolve, reject) => {          axios.post(url, params)             .then(response => {               resolve(response.data);  }) .catch((error) => {        reject(error);       })    })  }  export default {    // 获取我的页面的后台数据      mineBaseMsgApi() {        // alert('进入api.js')          return fetch('/api/getBoardList');      },      commonApi(url, params) {        return fetch(url, params)      }  }
在store的入口文件index.js中:
  // 组装模块并导出 store 的文件  import Vue from 'vue'  import Vuex from 'vuex'  import mine from './modules/mine';  import club from './modules/club';  Vue.use(Vuex);  // 导出需要的模块  export default new Vuex.Store({      modules: {          club,          mine     }  });
一般在项目中,我们跟在交互的时候,无非是存数据和取数据。首先我们来看存数据:
1:在你需要请求后台数据并想使用vuex的组件中的created分发第一个dispatch:
  created() {      // 保存IDvuex,在购买页面使用      this.$store.dispatch('storeMovieID',this.$route.params.ID)——(“action名”,data);      api.commonApi('url','params')          .then(res => {              this.backMsg = res.data;              console.log(this.backMsg);              console.log('调用封装后的axios成功');          })  },
2:然后在store/modules下的对应模块js文件中,这里我使用的club.js文件中编写state、action和mutation(一般为了方便,我们会习惯的把action里面的名字以驼峰式命名,而mutation里面的命名,我们会采用全大写+下划线的命名方式)actions 用来触发mutations,action可以进行异步操作 ,在action里可以用commit提交mutations
  const actions = {      // 保存ID  storeMovieID为上面的"action"      storeMovieID({ commit }, res) {          //此处是触发mutation STORE_MOVIE_ID"mutation"          commit(types.STORE_MOVIE_ID, res);      },  }
3:我们需要在type.js里面定义常量:
// ID 变量名(大写)=‘常量名(大写)’export const STORE_MOVIE_ID = 'STORE_MOVIE_ID';
4:通过mutation修改state中的数据:
//mutation名常量定义 并且需要在type.js文件下定义常量const mutations = {    // 修改ID 中括号代表常量 [types.常量名]    [types.STORE_MOVIE_ID]( state, res) {        state.movieID = res;      //state.数据名 = data    },}
5:定义state数据:(数据名:初始值)
const state = {       //采用 数据名:初始值的格式    contextPathSrc: '后台接口公共部分',    movieID: '',}
最后所有的club.js完整内容如下:(当然getters是在取数据的时候用的,下面会讲)
import api from './../../fetch/api';import * as types from './../types.js';// state 是vuex 保存数据的,就相当于vue里的dataconst state = {    contextPathSrc: '后台接口公共部分',    movieID: '',}const actions = {    // 保存ID  storeMovieID为上面的"action"    storeMovieID({ commit }, res) {        //此处是触发mutation STORE_MOVIE_ID"mutation"        commit(types.STORE_MOVIE_ID, res);    },}const getters = {    // 图片公共 src 的获取 getter函数:state=> state.数据名    getContextPathSrc: state => state.contextPathSrc,    // 获取ID    movieID: state => {        if(state.movieID == ''){            return localStorage.getItem('STORE_MOVIE_ID');        }else{            return state.movieID;        }    },}//mutation名常量定义 并且需要在type.js文件下定义常量 mutations 用来向state提交数据的,只能进行同步操作const mutations = {    // 修改ID 中括号代表常量 我们可使用ES2015风格的计算属性命名功能来使用一个常量[types.STORE_MOVIE_ID]作为函数名    [types.STORE_MOVIE_ID]( state, res) {        state.movieID = res;    },}export default {    state,    actions,    getters,    mutations}
下边我们要说的是取数据并且渲染到页面中,或者在页面函数中使用的方法:
1:组建中你需要导入如下:
  import { mapGetters } from 'vuex';
在组件的计算属性中,如下:
  computed: {    ...mapGetters([//...函数名 使用对象展开运算符将此对象混入到外部对象中        'getContextPathSrc'      ])  },
这里的getContextPathSrc函数,在页面中可直接使用,如果在函数中使用,需要this.getContextPathSrc
2:最后在store中写getters函数:
  const getters = {      // 图片公共 src 的获取 getter函数:state=> state.数据名      getContextPathSrc: state => state.contextPathSrc,  }
最后在页面渲染就可以了。。这样就完成了交互。可能有人会留意到上面的getters里的movieID函数有个if判断,最后
  return localStorage.getItem('STORE_MOVIE_ID')


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
vuex——模块化
vuex知识点
Vuex下Store的模块化拆分实践
vue 首屏优化
成功使用vue store存取全局变量
在vue-element-admin中使用Vuex
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服