乱七八糟的笔记,仅仅是个人学习使用
不用往下看,浪费时间
路由与组件
一个路由对应一个组件,是一一对应的映射关系
引入vue与vue-router库
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
实例化vue-router
const router = new VueRouter({
routes
})
挂载到根vue实例
// 从而让整个应用都有路由功能
const app = new Vue({
router
}).$mount('#app')
创建路由对应的组件
const Foo = {
template: '<div>foo</div>' }
const Bar = {
template: '<div>bar</div>' }
配置路由
const routes = [
{
path: '/foo', component: Foo },
{
path: '/bar', component: Bar }
]
定义路由出口
<router-view></router-view>
<router-view class="view two" name="a"></router-view>
路由跳转
//标签
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
// 字符串
router.push('home')
// 对象
router.push({
path: 'home' })
// 命名的路由
router.push({
name: 'user', params: {
userId: '123' }})
// 带查询参数,变成 /register?plan=private
router.push({
path: 'register', query: {
plan: 'private' }})
// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)
路由元信息
$route.params
路由传递参数
//使用:
const User = {
template: '<div>User {
{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
{
path: '/user/:id', component: User }
]
})
//获取 $route.params
//下面几种都是获取都是通过 props
//使用:
const User = {
props: ['id'],
template: '<div>User {
{ id }}</div>'
}
const router = new VueRouter({
routes: [
{
path: '/user/:id', component: User, props: true },
// 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
{
path: '/user/:id',
components: {
default: User, sidebar: Sidebar },
props: {
default: true, sidebar: false }
}
]
})
//使用:
const router = new VueRouter({
routes: [
{
path: '/promotion/from-newsletter', component: Promotion, props: {
newsletterPopup: false } }
]
})
//使用
const router = new VueRouter({
routes: [
{
path: '/search', component: SearchUser, props: (route) => ({
query: route.query.q }) }
]
})