主頁面
<template> <div> <ul v-for="item in courseList"> <router-link :to="{ name:index,query:{id:item.id} }">{{ item.title }}</router-link> </ul> </div> </template> <script> export default { name: "Couerse", data() { return { index: "CourseDetail", courseList: "" }; }, // 頁面剛加載立即執行 = mounted
// mounted:在模板渲染成html后調用
mounted() { this.initCourse(); }, methods: { //這個方法也可以跳轉 handleClick(ret) { this.$router.push({ path: `/CourseDetail/${ret}/`, query: { page: ret, code: "8989" } }); }, //通過ajax向接口發送請求並獲取課程列表 //axios/jquery // npm install axios --save // 第一步:在main.js中配置 //第二步:使用axios發送請求 initCourse: function() { // 記住一點要定義一個全局的 this 來取值 var _this = this; this.$axios .request({ url: "http://127.0.0.1:8000/api/v1/course/", methods: "GET" }) .then(function(ret) { // ajax請求發送成功后,獲取的響應內容 // ret.data= if(ret.data.code === 1000){ _this.courseList = ret.data.data; } }) .catch(function(ret) { // ajax請求發送失敗后,獲取的響應內容 }); } } }; </script> <style scoped> </style>
跳轉后的頁面
<template> <div> <img :src="detail.img" /> <h1>{{ detail.title }}</h1> <h3>{{detail.slogon }}</h3> <h5>{{ detail.level }}</h5> <p>{{ detail.why }}</p> <div> <ul v-for="item in detail.chapter"> <li>{{ item.title }}</li> </ul> </div> <br/> 推薦課程: <div> <ul v-for="item in detail.recommends"> <li>{{ item.title }}</li> </ul> </div> </div> </template> <script> export default { name: "CourseDetail", data() { return { detail: { course: null, img: null, level: null, slogon: null, title: null, why: null, chapter: [], recommends: [] } }; }, // created:在模板渲染成html前調用 created() { this.getRouterData(); }, methods: { getRouterData() { // 拿到主頁面傳過來的id值 this.id = this.$route.query.id; // 發送ajax請求給后端 請求詳細信息
//獲得一個全局的this
var _this = this; this.$axios .request({ url: `http://127.0.0.1:8000/api/v1/coursedetail/${this.id}/`, methods: "GET" }) .then(function(ret) { // ajax請求發送成功后,獲取的響應內容 // ret.data= if (ret.data.code === 1000) { _this.detail = ret.data.data; } }) .catch(function(ret) { // ajax請求發送失敗后,獲取的響應內容 }); } } }; </script> <style scoped> </style>