1. 程式人生 > >Vue.js--基於$.ajax獲取資料並與元件的data繫結

Vue.js--基於$.ajax獲取資料並與元件的data繫結

Vue.js與jQuery不衝突???

在實際的應用中,幾乎90%的資料是來源於服務端的,前端和服務端之間的資料互動一般是通過ajax請求來完成的。
說到ajax請求,第一反應肯定想到了jQuery,專案中如果引入jQuery會幫助我們簡化很多操作,簡化DOM操作,ajax方法獲取後端資料等。
然而,Vue.js和jQuery衝突嗎???
答案顯然是不衝突!!!
接下來會實現Vue.js元件中使用jQuery的ajax方法獲取伺服器端資料並繫結至元件的data中。

建立Vue.js單檔案元件

<template>
    <div>
        <div
class="id">
{{ret}}</div> <div class="id">{{data}}</div> </div> </template> <script> export default{ name:'Test', data(){ return{ ret:'', data:'' } }, mounted(){ this
.$nextTick(()=>{ var that=this; $.ajax({ type:"get", url:"//wuanlife_api/index.php/Post/get_collect_post", data:{user_id:1}, success:function(data){ that.ret=data.ret; that.data=data.data; } }) }) } }
</script> <style> .id{ font-size: 25px; position: relative; left:50px; right:50px; } </style>

json資料

{"ret":200,"data":{"page_count":1,"current_page":1,"posts":[]},"msg":null}

頁面效果

這裡寫圖片描述

在ajax獲取資料後將獲取到的資料繫結到元件物件的data上,就能完成資料的獲取。

這樣頁面中就能正確的使用從伺服器端獲取的資料來渲染了。