Vue中在新窗口打开页面及Vue-router的使用

2020-06-14 06:20:04易采站长站整理

背景

在开发提分加项目的过程中,遇到了点击下拉菜单时在新窗口中打开页面,由于之前一直做的是单页面应用,没有碰到过类似的需求,于是上网搜了一下解决办法,也再次系统地温习了一下vue-router。

下拉菜单

新窗口

解决

使用路由对象的resolve方法解析路由,可以得到location、router、href等目标路由的信息。得到href就可以使用window.open开新窗口了。


const {href} = this.$router.resolve({
name: "statistics-explain",
params: {
classID: id,
examSubjectID: this.planClassData.examSubjectID,
studentStatus: 0
}
});
window.open(href, '_blank');

延伸

参考文章:Vue Router

•动态路由匹配:一个“路径参数”使用冒号:标记。当匹配到一个路由时,参数值会被设置到this.$route.params,可以在每个组件内使用。

•嵌套路由:要在嵌套的出口中渲染组件,需要在 VueRouter 的参数中使用 children 配置,要注意,以 / 开头的嵌套路径会被当作根路径。 这让你充分的使用嵌套组件而无须设置嵌套的路径。


export default {
path: '/scoreplus',
name: 'scoreplus',
component: { template: '<router-view />' },
redirect: { name: 'scoreplus-index' },
children: [
{
// 查看个人方案
path: 'preview/:examSubjectID/:xuexinID/:recordsID/:constitute/:planID',
name: 'score-preview',
meta: { text: '个人方案' },
component: ScorePreview
},
{
// 查看方案内容
path: 'planList/:planID',
name: 'score-plan-list',
meta: { text: '查看方案内容' },
component: ScorePlanList
},
{
// 下载方案内容
path: 'download/:planID/:classID',
name: 'score-download-list',
meta: { text: '下载方案内容' },
component: DownloadList
},
{
// 查看推送试题
path: 'push/:planID/:level',
name: 'score-question-push',
meta: { text: '查看推送试题' },
component: QuestionPush
},
{
// 提分方案首页
path: '',
name: 'scoreplus-index',
component: ScoreIndex
}
]}

•编程式导航

1.router.push(location, onComplete?, onAbort?):想要导航到不同的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。


// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })