javascript - VUE2.0 切換詳情頁數據
問題描述
列表頁點擊到詳情可以正常根據id切換詳情內容列表頁:click函數添加 this.$router.push({ name: ’detail’, params: { id: id }});詳情接收傳遞過來的id this.$route.params.id,
列表頁右欄做了個導航(熱門文章),點擊熱門文章切換詳情內容問題是:地址欄:xx/detail/id可以正常傳遞,詳情內容沒變化正常hash有變化就應該更改對應的詳情數據,熱門文章點擊,雖然hash變了,詳情頁面只加載了一次哪位vue大神可以給講下原因啊
具體三個頁面的代碼:APP.vue
<template> <p id='app'> <router-view></router-view> </p> <aside> <hotList></hotList> </aside></template><script type='text/ecmascript-6'> import Vue from ’vue’ import artList from ’./components/artList.vue’ import hotList from ’./components/hotList.vue’ export default { name:’app’, components: { hotList, artList } }</script>
hotList.vm ,,hotList.vm和artList.vm的代碼邏輯一樣的
<template> <p class='hotlist'> <ul> <li v-for='(item,index) in items' @click='goDetail(item.id)'> {{ item.title }} </li> </ul> </p></template><script type='text/ecmascript-6'> export default { name:’hotlist’, data () { return {items: null, } }, mounted: function(){ this.$http.get(’/api/list’).then( function (response) {this.items = response.data }, function(error) {console.log(error) }) }, methods:{ goDetail(id){this.$router.push({ name: ’detail’, params: { id: id }}); }, } }</script>
detail.vue
<template> <p class='detail'> <h2>{{detail.title}}</h2> <p>{{ detail.description }}</p> </p></template><script type='text/ecmascript-6'> export default { name:’detail’, data () { return {listId: this.$route.params.id,detail: {}, } }, mounted: function(){ this.getDetail(); }, methods: { getDetail(){this.$http.get(’/api/list/’ + this.listId) .then(function (res) { this.detail = res.data.id ? res.data : JSON.parse(res.request.response); }.bind(this)) .catch(function (error) { console.log(error); }); }, } }</script>
路由:
import artListfrom ’../components/artList.vue’import detail from ’../components/detail.vue’const router = new VueRouter({ routes:[ { path:’/home’, name: ’home’, component: artList, }, { path: ’/home/artList/detail/:id’, name: ’detail’, component: detail, } ] }); export default router;
問題解答
回答1:初步估計問題出在detail.vue組件中。你的detail.vue的listId項的賦值出現了問題,嘗試這樣試一下:
export default { data () {return { listId: ’’} },mounted () {// 1.組件初步加載時賦值一次this.listId = this.$route.params.id; },watch: {’$route’: function () { //2. $route發生變化時再次賦值listId this.listId = this.$route.params.id;} }}
這樣組件初次加載的時候可以保證拿到正確的路由參數,在路由發生變化的時候也可以正確的拿到路由參數。
相關文章:
1. python - 獲取到的數據生成新的mysql表2. javascript - js 對中文進行MD5加密和python結果不一樣。3. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現 4046. python - (初學者)代碼運行不起來,求指導,謝謝!7. 為啥不用HBuilder?8. python - flask sqlalchemy signals 無法觸發9. python的文件讀寫問題?10. 為什么python中實例檢查推薦使用isinstance而不是type?
