【Vue】路由 - vue-router - SPA - 基本路由 - 嵌套路由 - 编程式路由导航

1. 理解

1.1. 说明

  1. 官方提供的用来实现SPA 的vue 插件
  2. github: https://github.com/vuejs/vue-router
  3. 中文文档: http://router.vuejs.org/zh-cn/
  4. 下载: npm install vue-router --save

1.2. 相关API 说明

  1. VueRouter(): 用于创建路由器的构建函数
new VueRouter({
    
    
// 多个配置项
})
  1. 路由配置
routes: [
	{
    
     // 一般路由
		path: '/about',
		component: About
	},
	{
    
     // 自动跳转路由
		path: '/',
		redirect: '/about'
	}
]
  1. 注册路由器
import router from './router'
new Vue({
    
    
	router
})
  1. 使用路由组件标签
  1. <router-link>: 用来生成路由链接
<router-link to="/xxx">Go to XXX</router-link>
  1. <router-view>: 用来显示当前路由组件界面
<router-view></router-view>

2. 基本路由

2.1. 效果

在这里插入图片描述

2.2. 路由组件

在这里插入图片描述
Home.vue
About.vue

2.3. 应用组件: App.vue

<template>
  <div>
    <div class="row">
      <div class="col-xs-offset-2 col-xs-8">
        <div class="page-header"><h2>Router Test</h2></div>
      </div>
    </div>

    <div class="row">
      <div class="col-xs-2 col-xs-offset-2">
        <div class="list-group">
          <!--生成路由链接-->
          <router-link to="/about" class="list-group-item">About</router-link>
          <router-link to="/home" class="list-group-item">Home</router-link>
        </div>
      </div>
      <div class="col-xs-6">
        <div class="panel">
          <div class="panel-body">
            <!--显示当前组件-->
            <keep-alive>
              <router-view msg="abc"></router-view>
            </keep-alive>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

2.4. 路由器模块: src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'

import About from '../pages/About'
import Home from '../pages/Home'

Vue.use(Router)

export default new Router({
    
    
  routes: [
    {
    
    
      path: '/about',
      component: About
    },
    {
    
    
      path: '/home',
      component: Home
    },
    {
    
    
      path: '/',
      component: About
    }
  ]
})

2.5. 注册路由器: main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    
     // 配置对象的属性名都是一些确定的名称,不能随便修改
  el: '#app',
  router,
  components: {
    
     App },
  template: '<App/>'
})

2.6. 优化路由器配置

linkActiveClass: 'active', // 指定选中的路由链接的class

2.7. 总结: 编写使用路由的3 步

  1. 定义路由组件
  2. 注册路由
  3. 使用路由
<router-link>
<router-view>

3. 嵌套路由

3.1. 效果

在这里插入图片描述

3.2. 子路由组件

在这里插入图片描述

News.vue

<template>
  <ul>
    <li v-for="(news, index) in newsArr" :key="index">{
   
   { news }}</li>
  </ul>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      newsArr: ["news001", "news002", "news003", "news004"],
    };
  },
};
</script>

<style>
</style>

Message.vue

<template>
  <ul>
    <li v-for="message in messages" :key="message.id">
      <a href="#">{
   
   { message.title }}</a>
    </li>
  </ul>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      messages: [],
    };
  },
  mounted() {
     
     
    //模拟ajax请求从后台获取数据
    setTimeout(() => {
     
     
      const messages = [
        {
     
     
          id: 1,
          title: "message001",
        },
        {
     
     
          id: 2,
          title: "message002",
        },
        {
     
     
          id: 3,
          title: "message003",
        },
      ];
      this.messages = messages;
    }, 1000);
  },
};
</script>

<style>
</style>

3.3. 配置嵌套路由: src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'

import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'

Vue.use(Router)

export default new Router({
    
    
  routes: [
    {
    
    
      path: '/about',
      component: About
    },
    {
    
    
      path: '/home',
      component: Home,
      children: [
        {
    
    
          // path: '/news' // path最左侧斜杠代表根路径
          path: '/home/news', //完整写法
          component: News
        },
        {
    
    
          path: 'message', // 简化写法
          component: Message
        },
        {
    
     //设置默认显示
          path: '',
          redirect: '/home/news'
        }
      ]
    },
    {
    
     //设置默认显示
      path: '/',
      redirect: '/about'
    }
  ]
})

3.4. 路由链接: Home.vue

<template>
  <div>
    <h2>Home</h2>
    <div>
      <ul class="nav nav-tabs">
        <li>
          <router-link to="/home/news">News</router-link>
          <router-link to="/home/message">Message</router-link>
        </li>
      </ul>

      <div>
        <router-view></router-view>
        <hr />
      </div>
    </div>
  </div>
</template>

<script>
export default {
     
     };
</script>

<style>
</style>

4. 向路由组件传递数据

4.1. 效果

4.2. 方式1: 路由路径携带参数(param/query)

  1. 配置路由
children: [
	{
    
    
	path: 'mdetail/:id',
	component: MessageDetail
	}
]
  1. 路由路径
<router-link :to="'/home/message/mdetail/'+m.id">{
   
   {m.title}}</router-link>
  1. 路由组件中读取请求参数
this.$route.params.id

4.3. 方式2: <router-view>属性携带数据

<router-view :msg="msg"></router-view>

然后组件用props接收

示例

MessageDetail.vue

<template>
  <ul>
    <li>id: {
   
   { messageDetail.id }}</li>
    <li>title: {
   
   { messageDetail.title }}</li>
    <li>content: {
   
   { messageDetail.content }}</li>
  </ul>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      messageDetail: {
     
     
        id: "",
        title: "",
        content: "",
      },
    };
  },
  mounted() {
     
     
    setTimeout(() => {
     
     
      const allMessageDetails = [
        {
     
     
          id: 1,
          title: "message001",
          content: "message001 content...",
        },
        {
     
     
          id: 2,
          title: "message002",
          content: "message002 content...",
        },
        {
     
     
          id: 3,
          title: "message003",
          content: "message003 content...",
        },
      ];
      this.allMessageDetails = allMessageDetails;
      const id = this.$route.params.id * 1;
      this.messageDetail = allMessageDetails.find((detail) => detail.id === id);
    }, 1000);
  },
  watch: {
     
     
    $route: function(value){
     
      // 路由路径(param)发生了改变
    const id = value.params.id * 1;
      this.messageDetail = this.allMessageDetails.find((detail) => detail.id === id);

    }
  }
};
</script>

<style>
</style>

index.js

import Vue from 'vue'
import Router from 'vue-router'

import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import MessageDetail from '../pages/MessageDetail'

Vue.use(Router)

export default new Router({
    
    
  routes: [
    {
    
    
      path: '/about',
      component: About
    },
    {
    
    
      path: '/home',
      component: Home,
      children: [
        {
    
    
          // path: '/news' // path最左侧斜杠代表根路径
          path: '/home/news', //完整写法
          component: News
        },
        {
    
    
          path: 'message', // 简化写法
          component: Message,
          children: [
            {
    
    
              path: '/home/message/detail/:id',
              component: MessageDetail
            }
          ]
        },
        {
    
     //设置默认显示
          path: '',
          redirect: '/home/news'
        }
      ]
    },
    {
    
     //设置默认显示
      path: '/',
      redirect: '/about'
    }
  ]
})

5. 缓存路由组件对象

5.1. 理解

  1. 默认情况下, 被切换的路由组件对象会死亡释放, 再次回来时是重新创建的
  2. 如果可以缓存路由组件对象, 可以提高用户体验

5.2. 编码实现

<keep-alive>
	<router-view></router-view>
</keep-alive>

6. 编程式路由导航

6.1. 效果

在这里插入图片描述

6.2. 相关API

  1. this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
  2. this.$router.replace(path): 用新路由替换当前路由(不可以返回到当前路由界面)
  3. this.$router.back(): 请求(返回)上一个记录路由
  4. this.$router.go(-1): 请求(返回)上一个记录路由
  5. this.$router.go(1): 请求下一个记录路由

示例

Message.vue

<template>
  <div>
    <ul>
      <li v-for="message in messages" :key="message.id">
        <!-- <a href="#">{
    
    { message.title }}</a> -->
        <router-link :to="`/home/message/detail/${message.id}`">{
   
   {
          message.title
        }}</router-link>
        <button @click="pushShow(message.id)">push查看</button>
        <button @click="replaceShow(message.id)">replace查看</button>
      </li>
    </ul>
    <button @click="$router.back()">回退</button>
    <hr />
    <router-view></router-view>
  </div>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      messages: [],
    };
  },
  methods: {
     
     
    pushShow(id) {
     
     
      this.$router.push(`/home/message/detail/${
       
       id}`);
    },
    replaceShow(id) {
     
     
      this.$router.replace(`/home/message/detail/${
       
       id}`);
    },
  },
  mounted() {
     
     
    //模拟ajax请求从后台获取数据
    setTimeout(() => {
     
     
      const messages = [
        {
     
     
          id: 1,
          title: "message001",
        },
        {
     
     
          id: 2,
          title: "message002",
        },
        {
     
     
          id: 3,
          title: "message003",
        },
      ];
      this.messages = messages;
    }, 1000);
  },
};
</script>

<style>
</style>

猜你喜欢

转载自blog.csdn.net/weixin_44972008/article/details/113921357