【Vue课序4】保姆级:Vuex异步数据获取

11 篇文章 1 订阅
7 篇文章 1 订阅
Store的解耦:

官方提供的是将Vuex注册在src/main.js下,但是为了后来项目store的解藕,我们采取一步到位式配置,参考辉哥React教案中react+redux的设计模式。


1.修改主store.js,用来集中管理主分支数据,其他分支数据通过import注入

import Vue from 'vue' // 引入 vue
import Vuex from 'vuex' // 引入vuex

// 引入分支store
import table from '@/page/table/store.js'

// 使用Vuex
Vue.use(Vuex);

// 创建并导出Vuex实例
export default new Vuex.Store({

    strict: true,
    devtools: true,
    plugins: [],
    modules: {
        table
    }

});

2.在src下创建 page文件夹,用来存放各自路由组件,page中一个文件夹对应一个路由(也就是对应一个页面

在这里插入图片描述


3.按”2步骤“在page中创建若干子文件夹,文件夹由以下构成:

  1. index.vue
  2. images ( 存放静态图片资源
  3. service.js ( 处理数据异步接口
  4. store.js ( 管理组件自己的store

4.当我们创建完一个pageindex.vue后一定要去/router文件夹中的index.js中注册路由。

import Vue from 'vue'
import Router from 'vue-router'

// 注册路由
import HelloWorld from '@/components/HelloWorld'
import Table from '@/page/table/index'

Vue.use(Router)

export default new Router({
    routes: [
    {
        path: '/',
        name: 'HelloWorld',
        component: HelloWorld
    },
    {
        path: '/Table',
        name: 'Table',
        component: Table
    }]
})

5.在config文件夹中创建的request.js

export const ip = 'http://127.0.0.1:8081';

export default function request(method, url, body, history) {

    method = method.toUpperCase();

    if (method === 'GET') {
        //fetch的GET不允许有body,参数只能放在url中
        body = undefined;
    } else {
        body = body && JSON.stringify(body);
    }

    return fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
        body: body
    }).then((res) => {
        if (res.status === 401) {
            history.push('/');
            return Promise.reject('Unauthorized.');
        } else {
            return res.json();
        }        
    });
}

export const get = url => request('GET', url);

export const post = (url, body) => request('POST', url, body);

6.修改service.js

// 只负责异步数据的export
// 相当于dva三大金刚service
import request from '@/../config/request'
import { ip } from '@/../config/request'

/*
* @Description: 获取表单数据
* @param: getMessageAcount
* @return: message
*/

export async function get_table(params) {

    let url = ip + '/web/user/rest/getMessageAcount'
    return request("POST", url, {
        cmd: 'getMessageAcount',
        type: 'request',
        request: {
            description: params.description
        }
    })
}

7.修改page目录下分支store.js

// 引入service的异步接口
import { get_table } from './service.js'

// 初始化分支数据
const state = {
    table: [ ]
}

// 在vuex中通过mutations更新store
const mutations = {

    get_table_success(state, payload) {

        // 相当于redux中更新reducer
        state.table = payload;

    },
    get_table_failed() { }
}


const actions = {

    // 异步请求await 需要加async ,相同于dva中的call
    async get_async(context, payload) {

		 // 异步操作,等待service的返回值
        const record = await get_table(payload); 
       

        if (record.response && record.response.res) {

            // 后台返回true的数据    
            let result = record.response.message;
			
			// 括号内指向mutations内的方法
            context.commit("get_table_success", result); 

        } else {

            // 后台返回false的数据
            context.commit(" get_table_failed");
        }
    }
}


export default {
    namespaced: true, // 声明分模块的store需要加上 
    state,
    mutations,
    actions
};

8.修改page目录中index.vue

<template>
    <div class="hello">
    <button v-on:click.stop="async_action()">异步请求</button>
    </div>
</template>

<script>
export default {

    name: "HelloWorld",

    data() {
        return {};

    },
    methods: {

        async_action() {

        // 括号参数分为两部分:
        // 斜杠前为对应的分支模块,斜杠后为分支模块对应的actions
        // 格式:模块名/模块中的mutations
        // 同样可以携带参数
        let description = "这是参数";

        this.$store.dispatch("table/get_async", description);

        }
    }
};
</script>

9.此时通过按钮点击已经完成了异步数据的获取以及更新到了store,接下来是如何进行页面渲染,在vuex中有一个类似于 mapDispatchToState的方法叫做 mapState, 下面是使用方法:

...mapState({
    a: "a"
}),

...mapState({
    _state: state => state
}), // 捕获外部状态 此时获取的是完整的store

...mapState(["test"]),    // 抓取test分支模块的完整数据

...mapState("test", ["isLogin”])     // 抓取test分支下的 “isLogin" 属性
以上都是 mapState的使用方法,但日常使用来说 后两者使用度更高。
来让我们接着完成index.vue中的模块
<template>
    <div class="hello">
        <button v-on:click.stop="async_action()">异步请求</button>
    </div>
</template>

<script>
import { mapState } from "vuex";
export default {
    
    name: "HelloWorld",

    data() {
        return {};
    },
    methods: {

        async_action() {
            // 括号参数分为两部分,斜杠前为对应的分支,斜杠后为分支对应的actions
            // 格式:模块名/模块中的mutations
            // 同样可以携带参数
            let description = "这是参数";
            this.$store.dispatch("table/get_async", description);

        }
    },

    // 注入外部store 类似于connect
    computed: {
        ...mapState(["table"])
        // ...mapState(['x']),   可以注入多个不同模块的store,根据实际情况注入
        // ...mapState(['xx']),
        // ...mapState(['xxx']),
    }
};
</script>
完成以上步骤已经实现了 页面发起异步请求->后台处理并返回数据->更新store->数据注入页面 一整套单向数据流。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值