Vue的生命周期及AJAX

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异步数据
在这里插入图片描述
在这里插入图片描述
页面的渲染效果如下
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值