vue2-axios

下载axios

开发版本:axios.js
生产版本:axios.min.js

搭建服务器:json-server

  • npm i -g json-server
  • json-server --watch db.json(启动服务并读取文件,db.json文件目录下启动)
    json-server --watch db.json --port 3000(指定端口)
  • 访问:
    http://localhost:3000(首页)
    http://localhost:3000/posts(读取文件所有数据)
    http://localhost:3000/posts/1(读取id为1的数据)
  • db.json
{
  "posts" : [
    {
      "title" : "title1",
      "anthor" : "anthor1",
      "id" : 1
    },
    {
      "title" : "title2",
      "anthor" : "anthor2",
      "id" : 2
    }
  ]
}

基本使用

<script src="../axios.js"></script>
<script src="../vue.js"></script>
<div id="app1">
    <button @click="search">get</button>
    <button @click="add">add</button>
    <ol>
        <li v-for="item in postList" :key="item.id">
            {{item.title}} {{item.author}}
            <button @click="remove(item.id)">delete</button>
        </li>
    </ol>
</div>
<script>
    // 设置url
    axios.defaults.baseURL = "http://localhost:3000";
    new Vue({
       el:'#app1', 
       data : {
           postList : []
       },
       methods : {
           search(){
               axios.get('/posts')
                   .then(res => {
                       console.log(res);// 请求成功
                       this.postList = res.data;
                   }).catch(reason => {
                       console.log(reason);// 请求失败
               });
           },
           add(){
               axios.post('/posts',{
                   title : "add",
                   author : "zhangsan"
               }).then(res => {
                   console.log(res);
               }).catch(reason => {
                   console.log(reason);
               });
           },
           // 异步写法
           async remove(id){
               try{
                   await axios.delete('/posts/' + id);
               }catch (e) {
                   console.log(e);
               }
           }
       }
    });
</script>

你可能感兴趣的:(javascript,vue)