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 官方推荐

fetch.js 

<script src="https://how2j.cn/study/vue.min.js"></script>
<script src="https://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>

axios.js

<script src="https://how2j.cn/study/vue.min.js"></script>
<script src="https://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>

 

posted @ 2020-09-07 17:33  野香蕉  阅读(79)  评论(0)    收藏  举报