故心故心故心故心小故冲啊
文章目录
一.全局组件定义
全局组件存放components文件夹中
引入全局组件在main.js中,这样就可以在所以组件中直接引入,不需要导入导出
// 引入全局自定义组件
import './components/global'
//index.js
import Vue from 'vue'
const componentsContext = require.context('./', true, /\.js$/);
console.log(componentsContext);
console.log(componentsContext.keys());
componentsContext.keys().forEach(component => {
const componentConfig = componentsContext(component);
// 兼容import export和require module.export两种规范
const ctrl = componentConfig.default || componentConfig;
// 加载全局组件
if (ctrl && ctrl.name) {
Vue.component(ctrl.name, ctrl);
// Vue.component('myComponent',{render(){return <h1>hello world</h1>}});
}
})
二.axios请求/拦截的封装
import axios from 'axios';
import { getToken } from '@/utils/token'
axios.defaults.baseURL = '基本url';
//请求拦截器
axios.interceptors.request.use(function (config) {
//在发送请求前
config.headers.token = getToken();
return config;
}, function (error) {
//请求错误
return Promise.reject(error)
});
//响应拦截器
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error)
});
export default axios; //直接返回axios;
三.本地存储封装
const tokenkey = 'token';
//存
export function setToken(token) {
return sessionStorage.setItem(tokenkey, token);
}
//取
export function getToken() {
return sessionStorage.getItem(tokenkey);
}
//删
export function removeToken() {
return sessionStorage.removeItem(tokenkey);
}
四.登录与退出接口的完成
import axios from '@/utils/request.js'
//登录
export function login(data) {
return axios({
method: 'post',
url: 'user/login',
data
})
}
//退出
export function logout() {
return axios({
method: 'post',
url: 'user/logout',
})
}
五.登录与退出调用接口
import { login } from "@/api/interface.js";
import { setToken } from "@/utils/token.js";
//登录
//提交表单
submitForm(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
//发送请求
login(this.form)
.then(res => {
//请求成功
console.log(res);
var { token } = res.data.data;
var { code } = res.data;
//把token存起来
setToken(token);
//登录判断
if (code == 20000) {
//登录成功,直接进入home页面
this.$message({
showClose: true,
message: "登录成功",
type: "success",
duration: 2000
});
this.$router.push("/home");
}
//登录失败
else {
this.$message({
showClose: true,
message: "账号或者密码错误",
type: "warning",
duration: 2000
});
}
})
.catch(err => {
//请求失败
console.log(err);
this.$message({
showClose: true,
message: "请求失败",
type: "warning",
duration: 2000
});
});
} else {
console.log("error submit!!");
return false;
}
});
},
import { logout } from "@/api/interface.js";
import { removeToken } from "@/utils/token.js";
//退出
goBack() {
//退出清除token
logout().then(res => {
console.log(res);
var { code } = res.data;
if (code == 20000) {
removeToken();
this.$message({
showClose: true,
message: "退出成功",
type: "success",
duration: 2000
});
this.$router.push("/login");
}
});
},