scrollBehavior 使用
HTML
<template>
<section class="recentto">
<Card title="最近创建的话题" :bordered="false" :dis-hover="true">
<CellGroup>
<article v-for="item in recentTo" :key="item.id">
<Avatar shape="square" :src="item.author.avatar_url" size="small" />
<span class="recentto-numbers">{{getReplyLen(item.id)}}/<span>{{getVisitLen(item.id)}}</span></span>
<router-link
:to="{name: 'Detail', params: {id: item.id}}"
class="recentto-tit ks-text-overflow"
:title="item.title"
>{{item.title}}</router-link>
<router-link :to="{name: 'Detail', params: {id: item.id}, hash: getLastReplyId(item.id)}" class="recentto-reply" v-if="getLastReplyAvatar(item.id)">
<Avatar shape="square" :src="getLastReplyAvatar(item.id)" size="small" />{{lastReplyTime(item.last_reply_at)}}
</router-link>
</article>
</CellGroup>
<a href="#" class="recentto-more" style="display: none;">
查看更多<Icon type="ios-arrow-forward" />
</a>
</Card>
</section>
</template>
CSS
//获取最后一条回复的 id
getLastReplyId(topicId){
let topic = this.details.find(obj => obj.id === topicId);
if(topic){
//该话题存在
let allReplies = topic.replies;
if(allReplies.length > 0){
//话题有回复
let hash = `#${allReplies[allReplies.length - 1].id}`;
return hash;
}else{
//话题没回复
return '';
}
}else{
//该话题不存在
return '';
}
}
Vue
import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/views/main/main';
import Detail from '@/views/detail/detail';
import User from '@/views/user/user';
import topNav from '@/router/topNav';
Vue.use(Router);
const scrollBehavior = (to, from, savedPosition) => {
if (savedPosition) {
// savedPosition is only available for popstate navigations.
return savedPosition;
} else {
const position = {}
// new navigation.
// scroll to anchor by returning the selector
if (to.hash) {
position.selector = to.hash
}
// check if any matched route config has meta that requires scrolling to top
if (to.matched.some(m => m.meta.scrollToTop)) {
// cords will be used if no selector is provided,
// or if the selector didn't match any element.
position.x = 0
position.y = 0
}
// if the returned position is falsy or an empty object,
// will retain current scroll position.
//console.log(position);
return position;
}
};
export default new Router({
mode: 'history',
scrollBehavior,
routes: [
...topNav,
{
path: '/main/:tab?',
name: 'Main',
component: Main
},
{
path: '/detail/:id',
name: 'Detail',
component: Detail
},
{
path: '/user/:loginname',
name: 'User',
component: User
},
{
path: '*',
redirect: '/'
}
]
})