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 - 请问这两个地方是为什么呢?2. sql语句 - 如何在mysql中批量添加用户?3. node.js - mysql如何通过knex查询今天和七天内的汇总数据4. mysql - JAVA怎么实现一个DAO同时实现查询两个实体类的结果集5. mysql建表报错,查手册看不懂,求解?6. mysql - PHP定时通知、按时发布怎么做?7. 怎么php怎么通过数组显示sql查询结果呢,查询结果有多条,如图。8. 事务 - mysql共享锁lock in share mode的实际使用场景9. mysql - 数据库建字段,默认值空和empty string有什么区别 11010. javascript - 按钮链接到另一个网址 怎么通过百度统计计算按钮的点击数量
