在上一節《vue+vue-router+axios+element-ui構建vue實戰項目之六(渲染index.vue列表)》中,我們從后端接口獲取數據,並成功渲染出一個列表。
這節內容,我們來做內容頁面。
編寫src/page/content.vue 文件
話不多說,直接上代碼
1 <template> 2 <div> 3 <h3>{{getMsg.title}}</h3> 4 <p>作者:{{getMsg.author.loginname}} 發表於:{{$utils.formatDate(getMsg.create_at)}}</p> 5 <hr> 6 <article v-html="getMsg.content"></article> 7 <h4>網友回復:</h4> 8 <ul> 9 <li v-for="item in getMsg.replies"> 10 <p>評論者:{{item.author.loginname}}, 發表於:{{$utils.formatDate(item.create_at)}}</p> 11 <article v-html="item.content"></article> 12 </li> 13 </ul> 14 </div> 15 </template> 16 <script> 17 export default { 18 data (){ 19 return { 20 id: this.$route.params.id, 21 getMsg: {} 22 } 23 }, 24 mounted (){ 25 this.getContent() 26 }, 27 methods:{ 28 getContent (){ 29 this.$http.get('topic/'+this.id) 30 .then(res => { 31 res.data.success && (this.getMsg = res.data.data) 32 }) 33 .catch(err => { 34 console.log(err) 35 }) 36 } 37 } 38 } 39 </script> 40 <style lang="scss"> 41 @import "../style/style"; 42 </style>
保存文件,然后我們隨便點開一篇文章,看到的結果如下:
好,按照我們的需求已經渲染出來了。
-_-!!,請忽略樣式!
講解下里面的重點部分
template部分
其他的內容,我們在列表頁面已經見過了。這里第一次出現 <article v-html="dat.content"></article> 這個東西。
同樣是渲染內容, v-html 和 v-text 有什么區別呢?
其實區別非常簡單,v-text 會把所有的內容當成字符串給直接輸出出來。
而 v-html 會把字符串給轉換為 html 標記語言給渲染出來。這部門更多內容,請參考:https://cn.vuejs.org/v2/api/#v-html
script部分
代碼基本上是一致的,重點是 id: this.$route.params.id,
這一句。
還記得我們前面配置的路由嗎?如果忘了,請移步vue+vue-router+axios+element-ui構建vue實戰項目之四(修改App.vue、router和page文件)
我們是這么配置的:
1 export default new Router({ 2 routes: [ 3 { 4 path: '/', 5 name: '首頁', //path別名,可刪除 6 meta:{ 7 title: '首頁' //設置頁面title 8 }, 9 component: index 10 }, 11 { 12 path: '/content/:id', 13 name: '詳情', 14 meta:{ 15 title: '詳情' 16 }, 17 component: content 18 } 19 ] 20 })
重點:path: '/content/:id', 中,我們使用了 :id 這個東西。
這是動態路由匹配。參考文檔: 《vue動態路由匹配》
我們需要從 url 中獲取 id, 然后根據這個 id 來進行數據的查詢。
從瀏覽器地址可以看到, url已經 包含了這個 id 。
http://localhost:8080/#/content/5c7e9a0d90c14711cc8ca9d8
如上:5c7e9a0d90c14711cc8ca9d8 這個就是 id。
我們如何取出來呢?
不用想很多復雜的事情,vue-router
早就給我們准備了解決方法了。
我們可以在項目中打印如下代碼:
console.log(this.$route)
打印結果,如圖
我們再看下我們的接口數據調用,代碼如下:
1 this.$http.get('topic/'+this.id) 2 .then(res => { 3 res.data.success && (this.getMsg = res.data.data) 4 }) 5 .catch(err => { 6 console.log(err) 7 })
等於沒什么要說的,就是把數據拿過來了而已,需要注意的是,我們的請求的接口地址是根據 id 進行變化的。
所以,我這邊采用了字符串拼接的方法,'topic/' + this.id 來得到我們真正想要請求的接口數據。
好,到這里為止,我們已經非常順利的把列表頁面和內容頁面已經渲染出來了!
如果我們按照這個步驟,相信你也順利的得到了一樣的結果。
如果文章中存在錯誤的地方,麻煩請大家在評論中指正,以免誤人子弟,謝謝!