这里有新鲜出炉的 vue.js 教程,程序狗速度看过来!
Vue.js 是构建 web 界面的 JavaScript 库,提供数据驱动的组件,还有简单灵活的 API,使得 MVVM 更简单。
这篇文章主要介绍了 vue+vuex+axio 从后台获取数据存入 vuex,组件之间共享数据, 非常具有实用价值,需要的朋友可以参考下
在 vue 项目中组件间相互传值或者后台获取的数据需要供多个组件使用的情况很多的话,有必要考虑引入 vuex 来管理这些凌乱的状态,今天这边博文用来记录这一整个的过程,后台 api 接口是使用 webpack-server 模拟的接口,这个前面的文章中有提到,需要的可以去翻阅。
整个的流程是在组件的 created 中提交 dispatch,然后通过 action 调用一个封装好的 axios 然后再触发 mutation 来提交状态改变 state 中的数据,然后在组件的计算属性中获取 state 的数据并渲染在页面上
首先新需要在项目中安装 vuex:
运行命令
- npm install vuex--save - dev
在项目的入口 is 文件 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'
- export
- function fetch(url, params) {
- return new Promise((resolve, reject) = >{
- axios.post(url, params).then(response = >{
- alert('Api--ok');
- resolve(response.data);
- }).
- catch((error) = >{
- console.log(error) reject(error)
- })
- })
- }
- export
- default {
- // 获取我的页面的后台数据
- mineBaseMsgApi() {
- alert('进入api.js') return fetch('/api/getBoardList');
- }
- }
在 store 的入口文件 index.js 中:
- import Vue from 'vue'import Vuex from 'vuex'
- import mine from './modules/mine';
- Vue.use(Vuex);
- export
- default new Vuex.Store({
- modules:
- {
- mine
- }
- });
在你需要请求后台数据并想使用 vuex 的组件中的 created 分发第一个 dispatch:
- created() {
- this.$store.dispatch('getMineBaseApi');
- }
然后在 store/modules 下的对应模块 js 文件中,这里我使用的 mine.js 文件中编写 state、action 和 mutation
- import api from './../../fetch/api';
- import * as types from './../types.js';
- const state = {
- getMineBaseMsg: {
- errno: 1,
- msg: {}
- }
- }
- const actions = {
- getMineBaseApi({
- commit
- }) {
- alert('进入action');
- api.mineBaseMsgApi().then(res = >{
- alert('action中调用封装后的axios成功');
- console.log('action中调用封装后的axios成功') commit(types.GET_BASE_API, res)
- })
- }
- }
- const getters = {
- getMineBaseMsg: state = >state.getMineBaseMsg
- }
- const mutations = { [types.GET_BASE_API](state, res) {
- alert('进入mutation');
- state.getMineBaseMsg = {...state.getMineBaseMsg,
- msg: res.data.msg
- }
- alert('进入mutations修改state成功');
- }
- }
- export
- default {
- state,
- actions,
- getters,
- mutations
- }
然后在想取回 state 的组件中使用 mapgetters 获取 state:
- import {
- mapGetters
- }
- from 'vuex';
- export
- default {...computed:
- {...mapGetters(['getMineBaseMsg'])
- },...}
然后在控制台查看把:
getter 和 mutation 都已经成功了,同时我在提交 state 的整个过程都添加了 alert,大家可以看看整个流程是如何走的。
来源: http://www.phperz.com/article/17/0618/333870.html