(十八)VueCli3.0全栈——加载动画和消息提醒

2019-07-10  本文已影响0人  彼得朱

因为我们在添加注册加载动画是请求注册,注册成功后提示动画,需要axios。

1、安装axios

2、设置请求响应拦截(因为用axios要用到请求和响应拦截)

import axios from 'axios';

// 请求拦截

//响应拦截

export default axios;

import axios from './http'

Vue.prototype.$axios = axios; //这句话设置之后所有的组件都能使用axios了

3、设置加载动画

import axios from 'axios';
import {Message,Loading} from 'element-ui';

let loading;

function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '拼命加载中...',
        background: 'rgba(0,0,0,0.7)'
    });
}

function endLoading() {
    loading.close();
}
// 请求拦截
// 请求的时候需要加载动画
axios.interceptors.request.use(
    config => {
    // 加载动画
    startLoading();
    return config;
    }, 
    error => {
        return Promise.reject(error);
    }
);

//响应拦截
axios.interceptors.response.use(
    response=>{
        // 结束加载动画
        endLoading();
        return response;
    },
    error=>{
        // 错误提醒
        endLoading();
        Message.error(error.response.data);
        return Promise.reject(error);
    }
)


export default axios;

4、配置跨域请求(vue-cli3.0的配置方法)

5、Registert.vue提交那里修改内容

methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {

            this.$axios.post("/api/users/register",this.registerUser)
            .then(res=>{
                // 注册成功
                this.$message({
                    message:'账号注册成功!',
                    type:'success'
                });
            })
            .catch(err=>{
                console.log(err);
            })

            // 注册成功,跳转
            // this.$router.push('/login');


        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }

6、测试

前端显示 数据库插入数据

注册成功。

上一篇 下一篇

猜你喜欢

热点阅读