Vue路由
前端路由和后端路由:
后端路由:对于普通的网站,所有的超链接都是url地址,所有url都对应服务器上对应的资源。
前端路由:对于单页面应用程序来说,主要通过url的hash(#)来实现不同页面的切换,同时hash还有一个特点HTTP请求中不会包含hash相关的内容,所以单页面程序中的页面跳转主要用hash实现。
在单页面应用程序中这种通过hash来改变页面的方式称作前端路由区别于后端路由。
路由的使用:
1、 创建一个路由对象,当导入vue-router包之后,在window全局对象中就有一个路由的构造函数VueRouter。
2、在new路由对象的时候可以传递一个配置对象,这个配置对象的route表示路由器的匹配规则。
3、每个路由规则都是一个对象,这个规则对象身上必须有两个属性:
属性1 path表示监听哪个路由链接地址。
属性2 component,表示如果路由是前面匹配到的path,则展示component属性对应的组件,component属性值必须是一个组件模板对象,不能是组件的引用名称。
4、router:routerObj将路由规则对象注册到VM实例上,用来监听URL地址的变化,然后展示对应的组件。
5、在控制的div中使用:
<router-view></router-view>
6、在搜索栏输入对应的匹配规则。
实例:
Home.vue:
<template>
<div>
<h3>你好冰冰,我是Home页</h3>
<br>
<!-- 取出动态路由的id值 -->
{{$route.params.id}}
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
</style>
router.js:
import Vue from 'vue' //引入vue对象
import Router from 'vue-router' //引入路由
import Home from './components/Home'
Vue.use(Router) //挂载 ,使用路由
export default new Router({ //导出一个路由对象,变量,,常量 ,函数 ,模块
mode: "hash", //设置路由样式 hash 默认值 http:localhost:8080/#/home
// mode:'history', http:localhost:8080/home
routes: [
{
path: '/home', //:id',组件的访问路径
name: 'home',
//1.常规引入方式
component: Home,
//2.懒加载引入方式
// component: () => import('./components/Home'),
// redirect: '/demovuex' //重定项到其他路由
},
{
path: '/parent',
component: () => import('./components/Parent'),//懒加载
children: [
{
path: '/child',
component: () => import('./components/Child'),
}
]
},
{
path: '/demovuex',
component: () => import('./components/DemoVuex'),
}
// {
// path: '/demovuex',
// component: () => import('./components/DemoVuex')
// }
]
})
main.js:
import Vue from 'vue'
import App from './App.vue'
//在入口程序中引入js文件
import router from './router'
// import store from './store/store' //
import store from './store2/index' // 引入带分模块的index.js
Vue.config.productionTip = false
//路由的守卫
router.beforeEach((to, from, next) => {
console.log(to.path) //打印被访问的路径
next(); //表示放行
})
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
结果是: