步骤 1 : Ajax
Vue.js 并没有限制使用哪种方式进行 ajax 访问,所以可以使用如下方式
- 原生 ajax
- JQuery
- vue-resource
- fetch.js
- axios.js
那么到底用哪种方式呢?
- 原生一般不在项目中直接用
- jquery 不如4,5方便
- vue-resource 已经不再维护了,所以不推荐
- fetch.js 是 vue.js 官方推荐
- 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>