在Vue中使用Ajax获取数据方式之一
一.axios的使用
- 浏览器自带的 fetch函数
- vue以前推荐的 vue-resource第三方模块
- 现在Vue推荐的 axios 第三方模块,axios非常强大,可以实现跨平台的数据请求,使用axios就先安装axios, 在终端运行 npm install axios --save
- 每一个组件都发一个Ajax请求会导致性能低,一个首页发一次Ajax请求。Ajax应该写在首页(比如home页面),在没有后端的情况下可以模拟一个数据,在static文件下新建一个mock文件->index.json,为什么放到这个文件呢,是因为这个文件可以直接访问,比如localhost:8080/static/mock/index.json.。
二.在首页代码如下
<template> <div> <home-header :city="city"></home-header> </div> </template> <script> // 留意组件的大小写 import HomeHeader from './components/Header' import axios from 'axios' export default { name: 'Home', components: { HomeHeader: HomeHeader }, data () { return { city: '' } }, methods: { getHomeInfo () { axios.get('/api/index.json') // 放回结果是一个promise对象 .then(this.getHomeInfoSucc) }, getHomeInfoSucc (res) { res = res.data if (res.ret && res.data) { const data = res.data this.city = data.city } } }, mounted () { this.getHomeInfo() } } </script>
三.在组件代码如下
<template> <div class="header-right"> {{this.city}} </div> </template> <script> export default { name: 'HomeHeader', props: { city: String } } </script>

浙公网安备 33010602011771号