zoukankan      html  css  js  c++  java
  • 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>
    
    
  • 相关阅读:
    一看就懂的Mybatis框架入门笔记
    一文了解有趣的位运算(&、|、^、~、>>、<<)
    探究如何永久更改Maven的Dynamic Web Project版本及pom.xml默认配置
    编译流程之仿真
    数字逻辑基础2
    1. FPGA内部的逻辑资源
    c++ 入门之深入探讨拷贝函数和内存分配
    c++入门之浅拷贝和深拷贝
    c++入门之详细探讨类的一些行为
    c++入门之类与内存
  • 原文地址:https://www.cnblogs.com/psyduck/p/14372740.html
Copyright © 2011-2022 走看看