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>
    
    
  • 相关阅读:
    Jmeter分布测试
    SQL命令
    Linux执行命令时遇到的些问题
    Linux常用命令总结
    Jenkins与SVN持续集成
    在linux上创建slave节点
    内网域名配置方法
    Java中重写与重载的区别
    MongoDB基本使用
    MongoDB安装
  • 原文地址:https://www.cnblogs.com/psyduck/p/14372740.html
Copyright © 2011-2022 走看看