vue.js 学习四 (基于vue-cli学习 axios获取数据)
1.基于vue-cli设置登录页面问题汇总
问题一:vuex加载不到
解决办法:
执行npm install --save vuex
参考:
https://blog.csdn.net/weixin_42116120/article/details/106387042
问题二:axios is not function
执行 npm install axios -S
问题三:axios作用
axios主要是用于向后台发起请求的,还有在请求中做更多是可控功能。
2.基于axios的页面请求功能
1第一步(代码参考下面三)
components下建立login.vue
2.第二步(不导入默认的好像不是axios的需要的jar)
导入axios
import axios from 'axios'
3.做一个http请求
axios({
method: 'post',
url: '/user/login',
data: _this.loginForm
}).then(res => {
console.log(res.data)
_this.userToken = 'Bearer ' + res.data.data.body.token
// 将用户token保存到vuex中
_this.changeLogin({ Authorization: _this.userToken })
_this.$router.push('/home')
alert('登陆成功')
}).catch(error => {
alert('账号或密码错误')
console.log(error)
})
3.完整的页面代码(components下建立login.vue)
<template> <div> <input type="text" v-model="loginForm.username" placeholder="用户名"/> <input type="text" v-model="loginForm.password" placeholder="密码"/> <button @click="login">登录</button> </div> </template> <script> import { mapMutations } from 'vuex' import axios from 'axios' export default { data () { return { loginForm: { username: '', password: '' } } }, methods: { ...mapMutations(['changeLogin']), login () { let _this = this if (this.loginForm.username === '' || this.loginForm.password === '') { alert('账号或密码不能为空') } else { axios({ method: 'post', url: '/user/login', data: _this.loginForm }).then(res => { console.log(res.data) _this.userToken = 'Bearer ' + res.data.data.body.token // 将用户token保存到vuex中 _this.changeLogin({ Authorization: _this.userToken }) _this.$router.push('/home') alert('登陆成功') }).catch(error => { alert('账号或密码错误') console.log(error) }) } } } } </script>
4.完整的js代码(router建立index.js)
import Vue from 'vue' import Router from 'vue-router' import login from '@/components/login' import HelloWorld from '@/components/HelloWorld' Vue.use(Router) const router = new Router({ routes: [ { path: '/', redirect: '/login' }, { path: '/login', name: 'login', component: login }, { path: '/HelloWorld', name: 'HelloWorld', component: HelloWorld } ] }) // 导航守卫 // 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆 router.beforeEach((to, from, next) => { if (to.path === '/login') { next() } else { let token = localStorage.getItem('Authorization') if (token === 'null' || token === '') { next('/login') } else { next() } } }) export default router
学习来源:
https://www.cnblogs.com/web-record/p/9876916.html
安装axios:
https://blog.csdn.net/weixin_42645490/article/details/109686766
axios作用:
https://www.cnblogs.com/yuanjili666/articles/11299759.html
BFF框架设计:
https://segmentfault.com/a/1190000020623009