Vue学习Day3:学习Element-UI组件库、Font Awesome图标库和Axios请求库。掌握Axios的GET、POST请求,了解async/await用法和全局配置。
学习笔记
Element-UI
饿了么开源的Vue组件库
URL: https://element.eleme.cn/
Font Awesome
图标库
URL: https://fontawesome.dashgame.com/
Axios
一个进行request请求的库
用法大概就是这样
export default {
created: function () {
axios.get("http://localhost:8088/user/findAll").then(function(response) {
console.log(response);
});
},
};- created表示 当页面组件创建时自动调用 具体见:生命周期选项:https://cn.vuejs.org/api/options-lifecycle.html#options-lifecycle
具体的一些细节
Get请求
axios.get("http://localhost:8088/user?ID=123")
.then(function (response) {
// 处理成功情况
console.log(response);
})
.catch(function (error) {
// 处理异常情况
console.log(error);
})
.then(function() {
// 总是会执行
});
// 参数部分等价于
axios.get("http://localhost:8088",{
params: {
ID: 123,
}
})Post 请求
axios.post("http://localhost:8088",{
username: "admin",
password: "123456"
})async/await
async和await必须成对出现。
解决异步回调问题
async function getUser() {
try {
const response = await axios.get("/uer");
console.log(response);
} catch(error) {
console.error(error);
}
}全局配置
// 配置请求根路径
axios.defaults.baseURL = "http://localhost:8088";
// 将axios作为全局的自定义属性,每个组件可以在内部直接访问(vue3)
app.config.globalProperties.$http = axios
// 将axios作为全局的自定义属性,每个组件可以在内部直接访问(Vue2)
Vue.prototype.$http = axios
添加以上配置 可以达到以下效果
// 不用每个组件内 import axios from "axios";
export default {
created: function () {
this.$http.get("/user/findAll").then((response) => {
console.log(response);
});
}
}用箭头函数而不用function创建函数的原因:作用域问题,用箭头函数作用域就跟created一样