vue.js 配置axios 用來ajax請求資料

來源:互聯網
上載者:User

標籤:find   cors   瀏覽器   安裝   直接   pat   axios   outer   組件   

* 用npm 安裝 axios

   切換到項目的根目錄

npm install --save axios vue-axios

  

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

// axiosimport 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‘// axiosimport 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請求資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.