如我们所知,vue是一个大型的单页面应用,它实际上可以看成是只有一个页面,那么很多人会问,不同页面的切换该如何做处理?
没错,靠的就是路由跳转vue-router了;
vue项目中的路由跳转有很多种方式,以下且听我细细说来~
npm install vue-router -D
安装完成后,在 src 文件夹下,创建一个 routers.js 文件,在该文件中引入所需的组件,创建 routers 对象:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/', //path配置路由的路径
name: 'HelloWorld', //映射的组件所对应的name
component: HelloWorld //配置映射的组件
}
]
})
最后再src/main.js中引入Vue-Router:
import router from './router'
new Vue({
el: '#app',
router,
components: { App },
template: ' '
})
此外,Vue-Router可以有相关的配置,在src/main.js中设置router:
mode属性:如果不配置 mode,就会使用默认的 hash 模式,该模式下会将路径格式化为 #! 开头;添加 mode: ‘history’ 之后将使用 HTML5 history 模式,该模式下没有 # 前缀,而且可以使用 pushState 和 replaceState 来管理记录。
const router = new VueRouter({
mode: 'history',
routes: routers
})
在项目中,根组件是app.vue。app.vue的部分代码如下:
<template>
<div id="app">
<router-view/>
div>
template>
而如果页面中有固定的部分如导航栏或者页脚,则可以如上代码中所写,导航栏和页脚是不会变的,而中间的
呃呃呃~跑远了,绕回来
我们知道,Vue项目中有父组件和子组件,子组件都会按需渲染到父组件的
{
path: '/home',
name: 'homePage',
component: homePage,
children:[
{
path: '/index1',
name: 'component_1',
component: component_1
},
{
path: '/index2',
name: 'component_2',
component: component_2
}
]
}
我想从homePage页面跳转到flexExample页面:
<template>
<div id="main">
<router-link to="/flex">跳转到flexExample页面router-link>
div>
template>
同样需求,从homePage页面跳转到flexExample页面
<template>
<div id="main">
<el-button type="primary" @click="toFlexExamplePage">
flex弹性布局el-button>
div>
template>
<script>
export default {
name: 'home-page',
methods:{
toFlexExamplePage:function(){
this.$router.push({
path:'/flex'
})
}
}
}
</script>
参考文章:https://www.cnblogs.com/wisewrong/p/6277262.html