Vue的生命周期
每个 Vue 实例在被创建时都要经过一系列的初始化过程
生命周期分为三大阶段:初始化显示、更新显示、销毁Vue实例
初始化阶段的钩子函数:
beforeCreate() 实例创建前:数据和模板均未获取到
created() 实例创建后: 最早可访问到 data 数据,但模板未获取到
beforeMount() 数据挂载前:模板已获取到,但是数据未挂载到模板上。
mounted() 数据挂载后: 数据已挂载到模板中
更新阶段的钩子函数:
beforeUpdate() 模板更新前:data 改变后,更新数据模板前调用
updated() 模板更新后:将 data 渲染到数据模板中
销毁阶段的钩子函数:
beforeDestroy() 实例销毁前
destroyed() 实例销毁后
liveServer 服务端插件
在VScode里面安装liveServer插件,用于ajax接口调用、
启动服务器:
方式1:任意打开一个 html 页面,在最下面可看到
点击它可启动,默认端口5500
方式2:在 html 页面单击右键 ,点击如下,访问页面
注意:如果之前启动过服务器,则使用 方式2 启动html页面,不能使用 方式1 会端口占用
更改 liveServer 默认端口号:
按 Ctrl + , 打开 Settings ,如下操作,打开 settings.json,
再json文件中添加 “liveServer.settings.port”: 8080,
Vue 中常用的 ajax 库
目前 Vue 官方没有内置任何 ajax 请求方法
vue-resource
在 vue1.x 版本中, 被广泛使用的非官方 Vue 插件 vue-resource
axios
在 vue 2+ 版本中,官方推荐使用非常棒的第三方 ajax 请求库
使用:结合生命钩子获取数据,渲染数据
vue-resource 的使用
参考的文档:https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
安装
npm install vue-resource
vue-resource使用手册: https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
{
// GET /someUrl
this.$http.get('/someUrl').then(response => {
// success callback
}, response => {
// error callback
});
}
传过来的json数据
Axios的使用
参考文档: https://github.com/axios/axios/blob/master/README.md
const axios = require('axios').default;
// axios.<method> will now provide autocomplete and parameter typings
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
测试使用
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
使用nodejs安装axios
npm install axios
在上次的bootstrap模板中使用axios异步数据
页面的渲染效果如下