导航栏

Vue(十)-- vue-ajax、ajax使用练习

1.vue-resource(了解)

  • 下载
    npm install vue-resource --save

  • 使用
    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>
	import axios from 'axios'
	export default{
		data(){
			return{
				repoUrl:'',
				repoName:''
			}
		},
		mounted(){
			//发ajax请求获取数据
			const url = 'https://api.github.com/search/repositories?q=vue&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>

需要在main.js中引入并使用resource

/* 
 入口js:创建Vue实例
 */
import Vue from 'vue'
import App from './App.vue'
import VueResource from 'vue-resource'

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

new Vue({
  el:'#app',
  components:{//将其映射成标签
    App
  },
  template:'<App/>'//使用组件标签
})

2.axios(重点)

  • 下载
    npm install axios --save

  • 使用
    和resource不同直接在需要使用axios的地方引入即可
    import axios from 'axios'
    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>
	import axios from 'axios'
	export default{
		data(){
			return{
				repoUrl:'',
				repoName:''
			}
		},
		mounted(){
			//发ajax请求获取数据
			const url = 'https://api.github.com/search/repositories?q=vue&sort=stars'
			//使用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>

posted @ 2021-02-04 15:13  RickZ  阅读(88)  评论(0编辑  收藏  举报