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>

相关文章