vue router-view使用详解

1、介绍

  router-view组件做为vue最核心的路由管理组件,在项目中做为路由管理常常被使用到。vue项目最核心的App.vue文件中便是经过router-view进行路由管理。javascript

<template>
  <div id="app">
      <router-view></router-view>
  </div>
</template>

咱们在本身维护项目的时候,也能够使用router-view组件进行路由管理,对于页面局部刷新的场景,该组件能发挥关键做用;html

2、使用方法

  咱们经过具体场景来介绍router-view组件用法:vue

1 实现效果

经过切换底部导航栏进行页面内容区域切换:
在这里插入图片描述
实现的功能是:点击消息、联系人、动态;页面内容进行切换;页面标题以及底部导航栏不变;java

2 代码

最关键的是router.js配置:app

{
    path: "/routerViewPractice",
    name: "routerViewPractice",
    component: () => import("@/views/routerView/index.vue"),
    redirect: '/messagePage',//页面默认加载的路由
    children: [
      {
        path: "/messagePage",
        name: "messagePage",
        component: () => import("@/views/routerView/childPages/messagePage.vue")
      },
      {
        path: "/contactPage",
        name: "contactPage",
        component: () => import("@/views/routerView/childPages/contactPage.vue")
      },
      {
        path: "/dynamicPage",
        name: "dynamicPage",
        component: () => import("@/views/routerView/childPages/dynamicPage.vue")
      }
    ]
  }

文件说明:flex

  • routerViewPractice:父路由path;
  • redirect:页面router-view组件默认加载的路由;
  • children:用于父页面进行切换的子路由;

vue父页面代码:this

<template>
  <div>
    <title-bar :title="title" @goBack="goback"></title-bar>
    <router-view></router-view>
    <BottomBar
     @handleMsg='handleMsg'
     @lookContact='lookContact'
     @readDynamic='readDynamic'
    ></BottomBar>
  </div>
</template>
<script>
import TitleBar from "@/components/TitleBar";
import BottomBar from "@/components/BottomBar";
export default {
  name: "",
  components: {
    TitleBar,
    BottomBar
  },
  data() {
    return {
      title: "路由视图",
    };
  },
  methods: {
    // 返回方法
    goback() {
      // this.$emit("GoBack");
    },
    handleMsg() {
      this.$router.push({path: '/messagePage'})
    },
    lookContact() {
      this.$router.push({path: '/contactPage'})
    },
    readDynamic() {
      this.$router.push({path: '/dynamicPage'})
    }
  }
};
</script>
<style scoped>
#page-title {
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
}
.backImg {
  width: 20px;
}
</style>

使用this.$router.push进行页面上router-view组件的路由替换;实现点击底部导航栏页面切换功能;spa