詳解通過JSON數(shù)據(jù)使用VUE.JS
最近接到一個(gè)比較簡單的項(xiàng)目,不準(zhǔn)備使用數(shù)據(jù)庫,打算用JSON數(shù)據(jù)就可以了。結(jié)合當(dāng)前火熱的VUE.JS進(jìn)行數(shù)據(jù)渲染。
盡管不打算使用數(shù)據(jù)庫,可是一般的操作增刪查改依舊是少不了的。如果使用到數(shù)據(jù)庫的話,不妨做一個(gè)API出來,那么網(wǎng)站、APP等都可以依照這個(gè)進(jìn)行操作。在這篇文章里面,我們只是打算簡單的引用而已。
下面先來看看我的JSON文件,這里是一個(gè)類別文檔Category.json:
{
"msg": "ok",
"data":[
{
"ID":"1",
"name": "地產(chǎn)",
"Url":"/Category/List/1"
},
{ "ID":"2",
"name": "科技",
"Url":"/Category/List/2"},
{ "ID":"3",
"name": "醫(yī)藥",
"Url":"/Category/List/3"},
{ "ID":"4",
"name": "其他",
"Url":"/Category/List/4"}
]
}
下面我們通過Javascript進(jìn)行渲染,將數(shù)據(jù)渲染到導(dǎo)航里面去。這里有兩種方式:如果你的項(xiàng)目已經(jīng)帶有JQuery的話,可以參考一下使用下面的代碼:
$(function(){
$.ajax({
type:'get',
url:'Category.json',
success: function(data){
if(data.msg == "ok"){
pushDom(data.data);
}
else
{
alert("服務(wù)器返回異常");
} },
error: function(data){
alert(JSON.stringify(data));
}
});
function pushDom(data1){
var vm = new Vue({ el: '#app', data: { peps:data1 } });
}
})
然后到html中,把數(shù)據(jù)渲染出來
<div id="app" class="inner">
<ul v-for = "pep in peps ">
<li><a href="{{pep.Url}}" rel="external nofollow" > {{pep.name}}</a></li>
</ul>
</div>
上面的代碼是使用JQuery的$.ajax 將json的數(shù)據(jù)引入,但如果你的項(xiàng)目里面沒有使用到JQuery的話,就要使用到vue-resource.js了。
在html中引入:
<script src="/js/vue.js"></script> <script src="/js/vue-resource.js"></script>
我第一次使用vue-resource.js的時(shí)候,和vue.js版本不匹配居然屢屢出錯(cuò),這是新手必須要注意的。這是一個(gè)坑啊,如果你們運(yùn)行下面的代碼不能渲染的話,99%是遇到這個(gè)坑了。
<script>
var app = new Vue({
el: '#app',
data: {
peps: ''
},
mounted: function() {
this.getJsonInfo()
},
methods: {
getJsonInfo: function() {
this.$http.get('Category.json').then(function(response){
console.log(response.data.data)
var resdata = response.data.data
this.peps = resdata
}).catch(function(response){
console.log(response)
console.log("居然沒有彈窗")
})
}
}
})</script>
html處不用做其它修改。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Vue.js常用指令匯總(v-if、v-for等)
- 淺談vue.js中v-for循環(huán)渲染
- Vue.js常用指令之循環(huán)使用v-for指令教程
- vue.js指令v-for使用以及下標(biāo)索引的獲取
- 深入淺析Vue.js 中的 v-for 列表渲染指令
- vue.js實(shí)現(xiàn)數(shù)據(jù)庫的JSON數(shù)據(jù)輸出渲染到html頁面功能示例
- 利用vue.js把靜態(tài)json綁定bootstrap的table方法
- vue.js學(xué)習(xí)筆記:如何加載本地json文件
- vue.js基于v-for實(shí)現(xiàn)批量渲染 Json數(shù)組對(duì)象列表數(shù)據(jù)示例
相關(guān)文章
vue實(shí)現(xiàn)簡單轉(zhuǎn)盤抽獎(jiǎng)功能
Vue3+cesium環(huán)境搭建的實(shí)現(xiàn)示例
vue-cli的webpack模板項(xiàng)目配置文件分析
如何解決sass-loader和node-sass版本沖突的問題
Vue實(shí)現(xiàn)自定義組件改變組件背景色(示例代碼)
在Vue使用$attrs實(shí)現(xiàn)構(gòu)建高級(jí)組件
Vue3中的element-plus表格實(shí)現(xiàn)代碼

