Ajax请求
1、 vue-resource(vue插件,非官方库,vue1.x使用广泛)
1.1、执行npm install vue-resource --save命令安装vue-resource插件
1.2、引入插件和声明使用插件
1.3、使用插件发Ajax请求
<template> <div id="app"> <div v-if="!repoName">loading...</div> <div v-else>most star repo is <a :ref="repoUrl">{{repoName}}</a></div> </div> </template> <script> export default { name: 'App', components: { }, data () { return { repoName: '', repoUrl: '' } }, mounted () { const url = 'https://api.github.com/search/repositories?q=v&sort=stars' // 使用vue-resource插件发Ajax请求 this.$http.get(url).then(response => { console.log(response) const repo = response.data.items[0] this.repoName = repo.name this.repoUrl = repo.html_url }, response => { console.log(response) alert(response.data.message) }) } } </script> <style> </style>
2、axios
2.1、执行命令npm install axios安装axios
2.2、引入axios(在哪里使用就在哪里引入)和使用axios
<template> <div id="app"> <div v-if="!repoName">loading...</div> <div v-else>most star repo is <a :ref="repoUrl">{{repoName}}</a></div> <div v-if="!repoName1">loading...</div> <div v-else>most star repo is <a :ref="repoUrl1">{{repoName1}}</a></div> </div> </template> <script> // 引入axios,在哪里使用就在哪里引入 import axios from 'axios' export default { name: 'App', components: { }, data () { return { repoName: '', repoUrl: '', repoName1: '', repoUrl1: '' } }, mounted () { const url = 'https://api.github.com/search/repositories?q=v&sort=stars' // 使用vue-resource插件发Ajax请求 this.$http.get(url).then(response => { console.log(response) const repo = response.data.items[0] this.repoName = repo.name this.repoUrl = repo.html_url }, response => { console.log(response) alert(response.data.message) }) // 使用axios发Ajax请求 axios.get(url).then(response => { console.log(response) const repo = response.data.items[0] this.repoName1 = repo.name this.repoUrl1 = repo.html_url }).catch(error => { console.log(error) }) } } </script> <style> </style>
相识是缘