vue.js 配置axios 用來ajax請求數據

* 用npm 安裝 axiosjavascript

   切換到項目的根目錄php

npm install --save axios vue-axios

  

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

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

  

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

// 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.jsonjava

{"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"}]}webpack

  爲何不能直接在組件中訪問 ../assets/data/people.json? ios

* php生成數據 (須要跨域CORS)web

<?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接口vue-router

php -S 0.0.0.0:8081

  

* 測試這個接口 能夠用瀏覽器訪問http://localhost:8081/person.phpnpm

  或者 命令行 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的文章也都沒有了。

相關文章
相關標籤/搜索