vue-router的详解

    科技2022-07-13  135

    为什么会使用Vue-router?

    因为现在大多采用单页面应用,Vue中会使用官方提供的Vue-router插件来使用单页面,原理就是通过检测地址栏变化后将对应的路由组件进行切换(卸载和安装)

    路由实现的步骤:

    1.cnpm install vue-router -S

    引入vue-router,如果是在脚手架中,引入VueRouter之后,需要通过 Vue.use来注册 import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) //内部调用了Router.install(Vue) 创建router路由器 let router = new Router({ routes:[ {path:"/home",component:Home} ] }) 创建路由表并配置在路由器中 var routes = [ {path,component}//path为路径,component为路径对应的路由组件 ] let router = new Router({ routes }) export default router 在根实例里注入router,目的是为了让所有的组件里都能通过this. r o u t e r 、 t h i s . router、this. routerthis.route来使用路由的相关功能api new Vue({ el: '#app', router, template: '<App/>', components: { App } }) 利用router-view来指定路由切换的位置使用router-link来创建切换的工具,会渲染成a标签,添加to属性来设置要更改的path信息,且会根据当前路由的变化为a标签添加对应的router-link-active/router-link-exact-active(完全匹配成功)类名 <router-link to="main">main</router-link> <router-link to="news">news</router-link> .router-link-active{ color:red; }
    Processed: 0.014, SQL: 8