vue-router的基本使用
映射组件和url
1.搭建路由框架
-
准备工作有已经装好vue-router。(通过npm install vue-router 或者在新建脚手架项目时直接选择安装)
-
在src/router/index.js中搭建基本的路由框架。
import Vue from 'vue'
import Router from 'vue-router'
import Title from './components/title'
import Result from './componemts/result'
//1.通过Vue.use(插件),安装插件,注意插件都需要在使用之前通过此方法
Vue.use(Router)
//2.创建Router对象,创建路由组件,配置路由映射
const routes=[
{
path: '/title',
component: Title
},
{
path:'/result',
component:Result
}
]
//3.导出Router对象传入Vue实例
export default new Router({
// 配置路由和组件之间的应用关系
routes,
//修改为HTML5模式
mode:'history',
//路由匹配成功情况下添加active的class
linkActiveClass;'active'
})
- 在main.js中注册路由
import Vue from 'vue'
import App from './App'
// 导入的是./router,但可以直接找到./router/index.js
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
})
- App.vue中使用两个标签改变url
<template>
<div id="app">
//router-link是注册过的全局组件,可以在任意地方使用
<router-link to="/title">标题</router-link>
<router-link to="/result">结果</router-link>
//router-view占位
<router-view></router-view>
</div>
</template>
2.使用vue-router
router-link是vue已经注册过的全局组件,最终会被渲染成a便签
**router-view用于占位 **
- 创建路由组件
在src/components下创建组件。此处创建了两个组件Result.vue和Title.vue。
<template>
<h3>我是result</h3>
</template>
<script>
export default {
name:"Result"
}
</script>
<style>
</style>
- 在src/router/index.js下配置路由映射,组件和路径映射关系
const routes=[
{
path: '/title',
component: Title
},
{
path:'/result',
component:Result
},
//重定向
path:'',
redirect: '/title]
- 在App.vue中通过和使用路由
<template>
<div id="app">
<!-- router-link是vue-router内置的全局组件,最终会被渲染成a标签 -->
<router-link to="/title">标题</router-link>
<router-link to="/result">结果</router-link>
<!-- router-view占位 -->
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
</style>
补充
1.router-link的一些属性。
tag:指定被渲染成什么组件,可以是button,li等。tag=“button”
replace:replace不会留下history记录,history.replaceState,故后退键不能返回上一个页面。
active-class:当对应的路由匹配成功(如按钮被点击),当前元素会有一个router-link-active的class,我们可以听过这个class设置如点击按钮字体变颜色等样式。
active-class=“active”
2.不使用而通过代码方式跳转路由
按钮绑定打击事件后在App.vue中写事件
methods:{ titileClick(){ //$router是自带的属性,每个组件都有这个属性,可以调用这个属性的方法 //或者通过replace() this.$router.push("/title") } }
动态路由
<router-link :to="'/user/'+userId"></router-link>
data(){
return {
userId:'zhangsan'
}
}
{path:'/user/:userId'
component:user}
this.$route.params.userId