看程序学Vue.js 15- VUE.JS 配合 FETCH.JS 或者 AXIOS.JS 进行 AJAX 访问

步骤 1 : Ajax
Vue.js 并没有限制使用哪种方式进行 ajax 访问,所以可以使用如下方式

  1. 原生 ajax
  2. JQuery
  3. vue-resource
  4. fetch.js
  5. axios.js

那么到底用哪种方式呢?

  1. 原生一般不在项目中直接用
  2. jquery 不如4,5方便
  3. vue-resource 已经不再维护了,所以不推荐
  4. fetch.js 是 vue.js 官方推荐
  5. axios.js 是vue.js 官方推荐
    步骤 2 : 首先准备 json 数组
    json 数据很简单,然后我把它放在:http://how2j.cn/study/jsons.txt 方便调用
    代码比较 复制代码

[
{“name”:“gareen”,“hp”:“355”},
{“name”:“teemo”,“hp”:“287”},
{“name”:“annie”,“hp”:“420”}
]
步骤 3 : fetch.js 方式

<script src="http://how2j.cn/study/vue.min.js"></script>
<script src="http://how2j.cn/study/fetch.min.js"></script>
  
<head>
<style>
table tr td{
    border:1px solid gray;
}
table{
    border-collapse:collapse;
    width:300px;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
 
</head>
<div id="div1">
    
    <table align="center" >
        <tr class="firstLine">
            <td>name</td>
            <td>hp</td>
        </tr>
          
        <tr v-for="hero in heros">
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
        </tr>
          
    </table>
  
</div>
  
<script>
var url = "http://how2j.cn/study/jsons.txt";
new Vue({
    el:'#div1',
    data:{
        heros:[]
    },
    mounted:function(){ //mounted 表示这个 Vue 对象加载成功了
        self=this
        fetch(url).then(function(response) {
            response.json().then(function (jsonObject) {
                self.heros = jsonObject
            })
        }).catch(function(err){
            console.log("Fetch错误:"+err);
        })
    }
})
</script>

步骤 4 : axios.js 方式

<script src="http://how2j.cn/study/vue.min.js"></script>
<script src="http://how2j.cn/study/axios.min.js"></script>
  
<head>
<style>
table tr td{
    border:1px solid gray;
}
table{
    border-collapse:collapse;
    width:300px;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
 
</head>
<div id="div1">
    
    <table align="center" >
        <tr class="firstLine">
            <td>name</td>
            <td>hp</td>
        </tr>
          
        <tr v-for="hero in heros">
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
        </tr>
          
    </table>
  
</div>
  
<script>
var url = "http://how2j.cn/study/jsons.txt";
new Vue({
    el:'#div1',
    data:{
        heros:[]
    },
    mounted:function(){ //mounted 表示这个 Vue 对象加载成功了
        var self = this
        axios.get(url).then(function(response) {
            self.heros= response.data; //此时还是字符串
            self.heros = eval("("+self.heros+")");  //字符串转换为数组对象
        })     
    }
})
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值