* 用npm 安装 axios

切换到项目的根目录

npm install --save axios vue-axios

  

* 在vue的入口文件./src/main.js 中引入axios, 添加2行代码

// axios
import axios from 'axios'
Vue.prototype.$http = axios

  

*  ./src/main.js 入口文件如下:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
// axios
import axios from 'axios'
Vue.prototype.$http = axios Vue.config.productionTip = false /* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})

* 生成数据文件./assets/data/people.json

{"people":[{"id":1,"name":"Jack","age":30,"gender":"Male"},{"id":2,"name":"Bill","age":26,"gender":"Male"},{"id":3,"name":"Tracy","age":22,"gender":"Female"},{"id":4,"name":"Chris","age":36,"gender":"Male"}]}

为什么不能直接在组件中访问 ../assets/data/people.json?

* php生成数据 (需要跨域CORS)

<?php
/**
* Test axios=> people.json
*/
header('Content-Type:text/json; charset=utf-8'); header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:GET');
header('Access-Control-Allow-Headers:x-requested-with,content-type'); $data = new \StdClass();
$data->people = [
[
"id" => 1,
"name" => "Jack",
"age" => 30,
"gender" => "Male"
],
[
"id" => 2,
"name" => "Bill",
"age" => 26,
"gender" => "Male"
],
[
"id" => 3,
"name" => "Tracy",
"age" => 22,
"gender" => "Female"
],
[
"id" => 4,
"name" => "Chris",
"age" => 36,
"gender" => "Male"
],
[
"id" => 5,
"name" => "guanmengying",
"age" => 29,
"gender" => "Female"
]
];
echo json_encode($data, true);

 * 启动php接口

php -S 0.0.0.0:8081

  

* 测试这个接口 可以用浏览器访问http://localhost:8081/person.php

或者 命令行 curl http://localhost:8081/people.php

输出:

{"people":[{"id":1,"name":"Jack","age":30,"gender":"Male"},{"id":2,"name":"Bill","age":26,"gender":"Male"},{"id":3,"name":"Tracy","age":22,"gender":"Female"},{"id":4,"name":"Chris","age":36,"gender":"Male"},{"id":5,"name":"guanmengying","age":29,"gender":"Female"}]}

* 路由文件 ./src/router/index.js

根据默认的HelloWorld照葫芦画瓢即可

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import person from '@/components/person' Vue.use(Router) export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/person',
name: 'person',
component: person
}
]
})

* 模板文件 ./src/components/person.vue

<template>
<div class="wrapper">
<fieldset>
<legend>
Create New Person
</legend>
<div class="form-group">
<label>Name:</label>
<input type="text" v-model="newPerson.name"/>
</div>
<div class="form-group">
<label>Age:</label>
<input type="text" v-model="newPerson.age"/>
</div>
<div class="form-group">
<label>gender:</label>
<select v-model="newPerson.gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="form-group">
<label></label>
<button @click="createPerson">Create</button>
</div>
</fieldset>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>gender</th>
<th>Delete</th>
</tr>
</thead>
<!-- 循环必须指定key -->
<tbody>
<tr v-for="(person) in people" :key="person.id">
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
<td>{{ person.gender }}</td>
<td :class="'text-center'">
<!-- <button @click="deletePerson($index)">Delete</button> -->
<button @click="deletePerson(person.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div> </template>
<style>
#app {
margin-top: 10px;
}
table {
margin: 20px auto;
}
</style>
<script>
export default {
name: "person",
created: function() {
var v = this;
v.$http
.get("http://localhost:8081/people.php")
.then(function(resp) {
v.people = resp.data.people;
})
.catch(function(error) {
document.write(error.toString());
});
},
data() {
return {
newPerson: {
name: "",
age: 0,
gender: "Male"
},
people: []
};
},
methods: {
createPerson: function() {
this.people.push(this.newPerson);
// 添加完newPerson对象后,重置newPerson对象
this.newPerson = { name: "", age: 0, gender: "Male" };
},
deletePerson: function(id) {
// find index
var index, person;
person = this.people.find(function(person, idx) {
var matchID = person.id === id;
if (matchID) {
index = idx;
}
return matchID;
});
// 删一个数组元素
this.people.splice(index, 1);
}
}
};
</script>

  主要的变更:

created: function() {
var v = this; // vue instance
v.$http
.get("http://localhost:8081/people.php") // xhr
.then(function(resp) {
v.people = resp.data.people; // bind data
})
.catch(function(error) {
document.write(error.toString());
});
},
data() {
return {
// ...
people: [] // empty array. null can cause template compiling error
};
},

  * 浏览器访问http://localhost:8080/#/person

csdn博客中插入 emoji 会导致后面的内容失效,要重新编辑。

https://emojipedia.org/smiling-face-with-sunglasses/ 所以不要用emoji

CSDN 的这个文章丢失了, 转存到这里。

而且在csdn创建的所有标签为vue的文章也都没有了。

vue.js 配置axios 用来ajax请求数据的更多相关文章

  1. 使用Vue.js和Axios从第三方API获取数据 — SitePoint

    更多的往往不是,建立你的JavaScript应用程序时,你会想把数据从远程源或消耗一个[ API ](https:/ /恩.维基百科.org /维基/ application_programming_ ...

  2. vue使用element Transfer 穿梭框实现ajax请求数据和自定义查询

    vue使用element Transfer 穿梭框实现ajax请求数据和自定义查询 基于element Transfer http://element-cn.eleme.io/#/zh-CN/comp ...

  3. JS 点击元素发ajax请求 打开一个新窗口

    JS 点击元素发ajax请求 打开一个新窗口 经常在项目中会碰到这样的需求,点击某个元素后,需要发ajax请求,请求成功以后,开发需要把链接传给前端(或者说请求成功后打开新窗口),前端需要通过新窗口打 ...

  4. js中使用队列发送ajax请求

    最近,项目中需要按照先后顺序发送ajax请求,并且在一次请求结束后才能发起下一次,不然就会导致逻辑错误. 解决办法是定义一个数组,保存ajax请求数据. 以下使用extjs4定义一个类 Ext.def ...

  5. 使用Python的Flask框架,结合Highchart,动态渲染图表(Ajax 请求数据接口)

    参考链接:https://www.highcharts.com.cn/docs/ajax 参考链接中的示例代码是使用php写的,这里改用python写. 需要注意的地方: 1.接口返回的数据格式,这个 ...

  6. Ajax请求数据的两种方式

    ajax 请求数据的两种方法,有需要的朋友可以参考下. 实现ajax 异步访问网络的方法有两个.第一个是原始的方法,第二个是利用jquery包的 原始的方法不用引入jquery包,只需在html中编写 ...

  7. session失效,使用ajax请求数据被拦截,此时正常的处理逻辑是跳到登录界面,而不是界面没有变化(java推断是否是ajax请求)

    在登录过滤器中.推断请求是ajax请求还是超链接或者地址栏变化的请求 if (httpServletReq.getHeader("x-requested-with") != nul ...

  8. 关于ajax请求数据,并将数据赋值给全局变量的一些解决方法

    在使用ajax请求数据是,开始的时候是打算将ajax的数据取出,并赋予给全局变量,但是在实际编码过程中发现并不能将数据赋予给最开始定义的全局变量,出现这个问题的原因是由于ajax异步加载的原因,所以只 ...

  9. h5-localStorage实现缓存ajax请求数据

    使用背景:要实现每次鼠标hover“能力雷达”,则显示能力雷达图(通过ajax请求数据实现雷达图数据显示),所以每次hover都去请求ajax会影响性能,因此这里要用到本地缓存. 实现: 此处是通过传 ...

随机推荐

  1. S3C2440—8.读写SDRAM

    文章目录 一.内部结构 二.相关寄存器 BWSCON BANKCON6 REFRESH BANKSIZE MRSR 三.读写SDRAM SDRAM:Synchronous Dynamic Random ...

  2. Spring-Boot注入自定义properties文件配置

    创建wzq.properties wzq.properties注入User实体类中 @PropertySource(value = "classpath:wzq.properties&quo ...

  3. 浅谈模拟彩票代码,html,javascript

    今天简单介绍一下用html,javascript来模拟双色球彩票选择器. 双色球彩票规则:由6个红球和1个蓝球组成,其中6个红球是从1-33中随机选出的不重复的6个数,从小到大一次排列:蓝球是1-16 ...

  4. 【译】JavaScript async / await:好的部分,陷阱和如何使用

    async/await提供了一种使用同步样式代码异步访问资源的选项,而不会阻塞主线程.然而,使用它有点棘手.在本文中,我们将从不同的角度探讨async / await,并将展示如何正确有效地使用它们. ...

  5. TaskAwaiter<TResult> 结构

    参考网址:https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.compilerservices.taskawaiter-1?view= ...

  6. C++ CLI简介(什么是C++ CLI)

    要知道C++/CLI是什么,首先知道什么是CLI. 一.CLI简介 CLI:(Common Language Infrastructure,通用语言框架)提供了一套可执行代码和它所运行需要的虚拟执行环 ...

  7. Json 文件 : 出现 Expected value at 1:0 问题的解决

    只要找一个json在线解析,验证你的json文件格式的正确性,错误可以忽略. 如要消除红叉,关闭Json Validation即可,如下操作:

  8. 分布式链路追踪系统Sleuth和ZipKin

    1.微服务下的链路追踪讲解和重要性 简介:讲解什么是分布式链路追踪系统,及使用好处 进行日志埋点,各微服务追踪. 2.SpringCloud的链路追踪组件Sleuth 1.官方文档 http://cl ...

  9. Spring源码解析之ConfigurationClassPostProcessor(三)

    在上一章笔者介绍了ConfigurationClassParser.doProcessConfigurationClass(...)方法,在这个方法里调用了processImports(...)方法处 ...

  10. unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source 解决办法

    Project -> Properties -> C/C++ -> Precompiled Headers -> Precompiled Header -> 选择Not ...