vue.js 配置axios 用来ajax请求数据

* 用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

阅读更多
文章标签: vue 前端框架
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭