1. 程式人生 > >vue中ajax應用

vue中ajax應用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        span.active{
            color:red;
        }
    </style>
</
head> <body> <div id="app"> <div> <span @click="handlerClick(index)" v-for = "(category,index) in categoryList" :key="category.id" :class="{active:index==currentIndex}"> <!--繫結屬性
--> {{ category.name }} </span> </div> </div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src='./vue.js'></script> <script> let vm = new Vue({ // 宣告變數 例項化一個物件vm(指的是vue的例項) el: "#app
", //繫結根元素 //資料屬性 data(){ //這裡有obsever //返回的資料跟後端資料庫裡的有關,如果是動態的資料,存的是資料結構 return {categoryList:[],currentIndex:0} }, methods:{ handlerClick(i){this.currentIndex=i;} }, created(){ $.ajax({ //請求後端資料 **** url:"https://www.luffycity.com/api/v1/course_sub/category/list/", type:"get", // success:function(data){ //後端資料渲染回來 success:(data)=>{ //data 一般是從後端返回給前端的 console.log(data); //Object //data:(6) [{…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer] //error_no:0 //proto__:Object if (data.error_no === 0){ var data=data.data; let obj={ id:0, name:"全部", category:"0" } this.categoryList = data; this.categoryList.unshift(obj) //把data賦值給categoryList console.log(this)//拿到的是一個ajax物件, // 所以把上面的匿名函式改成箭頭函式 //改成箭頭函式之後得到的是vue物件 this.categoryList=data; } }, error:function(err){ console.log(err); } }) } }) </script> </body> </html>