最近接到一個(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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
|
新聞熱點(diǎn)
疑難解答