Vue.js尚硅谷视频学习笔记(第三章:vue-ajax)

内容大部分文字描述来自尚硅谷课件,实例操作截图和注释内容为亲测。

第3 章:vue-ajax

3.1. vue 项目中常用的2 个ajax 库

3.1.1. vue-resource

vue 插件, 非官方库, vue1.x 使用广泛

3.1.2. axios

通用的ajax 请求库, 官方推荐, vue2.x 使用广泛

3.2. vue-resource 的使用

3.2.1. 在线文档

https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

3.2.2. 下载

npm install vue-resource --save

3.2.3. 编码

// 引入模块
import VueResource from 'vue-resource'
// 使用插件
Vue.use(VueResource)
// 通过vue/组件对象发送ajax 请求
this.$http.get('/someUrl').then((response) => {
	// success callback
	console.log(response.data) //返回结果数据
}, (response) => {
	// error callback
	console.log(response.statusText) //错误信息
})

实例:
main.js

import  Vue from 'vue'
import VueResource from 'vue-resource'
import App from './App.vue'

//声明使用插件
Vue.use(VueResource)
//内部会给vm对象和组件对象添加一个属性: $http(两个方法:get()和post())

new Vue({
    el: '#app',
    components: {App},
    template: '<App/>'
})

App.vue

<template>
  <div>
    <div v-if="!repoUrl">loading</div>
    <div v-else>most star repo is <a :href="repoUrl">{{repoName}}</a></div> 
  </div>
</template>



<script>
export default {
  data () {
    return {
      repoUrl: '',
      repoName: ''
    }
  },

  mounted() {
    //发Ajax请求获取数据
    const url = `https://api.github.com/search/repositories?q=v&sort=stars`

    this.$http.get(url).then(
      response => {
        //成功了
        const result = response.data
        //得到最受欢迎的repo
        const mostRepo = result.items[0]
        this.repoUrl = mostRepo.html_url
        this.repoName = mostRepo.name
      },

      response => {
        alert('请求失败')
      }
    )
  },
};
</script>

<style>

</style>

在这里插入图片描述
在这里插入图片描述

3.3. axios 的使用

在线文档

https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

下载:

npm install axios --save

编码

// 引入模块
import axios from 'axios'
// 发送ajax 请求
axios.get(url)
	.then(response => {
	console.log(response.data) // 得到返回结果数据
	})
	.catch(error => {
	console.log(error.message)
	})

App.js

扫描二维码关注公众号,回复: 5375006 查看本文章
<template>
  <div>
    <div v-if="!repoUrl">loading</div>
    <div v-else>
      most star repo is <a :href="repoUrl">{{ repoName }}</a>
    </div>
  </div>
</template>



<script>
import axios from "axios";

export default {
  data() {
    return {
      repoUrl: "",
      repoName: ""
    };
  },

  mounted() {
    //发Ajax请求获取数据
    const url = `https://api.github.com/search/repositories?q=v&sort=stars`;

    // this.$http.get(url).then(
    //   response => {
    //     //成功了
    //     const result = response.data;
    //     //得到最受欢迎的repo
    //     const mostRepo = result.items[0];
    //     this.repoUrl = mostRepo.html_url;
    //     this.repoName = mostRepo.name;
    //   },

    //   response => {
    //     alert("请求失败");
    //   }
    // );

    //使用axios发送ajax请求
    axios.get(url).then(
      response => {
        //成功了
        const result = response.data;
        //得到最受欢迎的repo
        const mostRepo = result.items[0];
        this.repoUrl = mostRepo.html_url;
        this.repoName = mostRepo.name;
      }).catch(error => {
        alert('请求失败')
      })
  }
};
</script>

<style>
</style>

3.4. 测试接口

接口1: https://api.github.com/search/repositories?q=v&sort=stars
接口2: https://api.github.com/search/users?q=aa

3.5. demo3: github users

在这里插入图片描述

main.js

import  Vue from 'vue'
import VueResource from 'vue-resource'
import App from './App.vue'

//声明使用插件
Vue.use(VueResource)
//内部会给vm对象和组件对象添加一个属性: $http(两个方法:get()和post())

new Vue({
    el: '#app',
    components: {App},
    template: '<App/>'
})

App.vue

<template>
  <div class="container">
    <Search/>
    <users-main/>
    
  </div>
</template>

<script>
import Search from './components/Search.vue'
import Main from './components/Main.vue'
export default {
  components: {
    Search,
    UsersMain: Main
  }
};
</script>

<style>
</style>

Main.vue

<template>
  <div>
    <h2 v-if="firstView">输入用户名搜索</h2>
    <h2 v-if="loading">LOADING...</h2>
    <h2 v-if="errorMsg">{{ errorMsg }}</h2>
    <div class="row">
      <div class="card" v-for="(user, index) in users" :key="index">
        <a :href="user.url">
          <img :src="user.avatar_url" style="width: 100px" />
        </a>
        <p class="card-text">{{ user.name }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import PubSub from "pubsub-js";
import axios from "axios";

export default {
  data() {
    return {
      firstView: true,
      loading: false,
      users: null, //[{url: '', avatar_url: '', name: ''}]
      errorMsg: ""
    };
  },

  mounted() {
    //是否在此发ajax请求   不是,而是在点击search之后

    //订阅搜索的消息
    PubSub.subscribe("search", (msg, searchName) => {
      //说明需要发ajax请求进行搜索
      const url = `https://api.github.com/search/users?q=${searchName}`;

      //更新状态
      this.firstView = false;
      this.loading = true;
      this.users = null
      this.errorMsg = ''

      //发ajac请求
      axios.get(url).then(response => {
        const result = response.data;
        const users = result.items.map(item => ({
          url: item.html_url,
          avatar_url: item.avatar_url,
          name: item.login
        }));
        //成功,更新状态(成功)
        this.loading = false;
        this.users = users;
      }).catch(error => {
          //失败,更新状态(失败)
          this.loading = false;
          this.errorMsg = `请求失败`
      })
      
    });
  }
};
</script>

<style>
.card {
  float: left;
  width: 33.333%;
  padding: 0.75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: 0.75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>

Search.vue

<template>
  <div>
    <section class="jumbotron">
      <h3 class="jumbotron-heading">Search Github Users</h3>
      <div>
        <input type="text" placeholder="enter the name you search" v-model="searchName" />
        <button @click="search">Search</button>
      </div>
    </section>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
export default {
  data () {
      return {
          searchName: ''
      }
  },

  methods: {
      search () {
        const searchName = this.searchName.trim()
        if(searchName) {
            PubSub.PubSub.publish('search', searchName)
        }
      }
  }
}
</script>

<style>

</style>

在这里插入图片描述

在这里插入图片描述在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/canxuezhang/article/details/87970721
今日推荐