您的位置:首页技术文章
文章详情页

javascript - VUE2.0 切换详情页数据

【字号: 日期:2023-03-23 11:27:19浏览:48作者:猪猪

问题描述

列表页点击到详情可以正常根据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;} }}

这样组件初次加载的时候可以保证拿到正确的路由参数,在路由发生变化的时候也可以正确的拿到路由参数。

标签: JavaScript
相关文章: