vue(17)vue-route路由管理的安装与配置

介绍

Vue RouterVue.js官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:css

  • 嵌套的路由/视图表
  • 模块化的、基于组件的路由配置
  • 路由参数、查询、通配符
  • 基于 Vue.js 过渡系统的视图过渡效果
  • 细粒度的导航控制
  • 带有自动激活的 CSS class 的连接
  • HTML5 历史模式或 hash 模式,在 IE9 中自动降级
  • 自定义的滚动条行为
     
安装

安装命令html

npm install vue-router --save

若是在一个模块化工程中使用它,必需要经过 Vue.use() 明确地安装路由功能:vue

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

 

模块化使用 watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

以前咱们使用脚手架vue-cli建立项目时,实际已经配置好了router,建立完项目后,在项目根目录下会有一个router文件夹,router下有一个index.js文件,内容以下:vue-router

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

// 1. 当咱们使用其余插件的时候,就必须使用Vue.use安装插件
Vue.use(VueRouter);

// 2. 定义路由,每一个路由应该映射一个组件
const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/about",
    name: "About",
    component: About
  },
];

// 3. 建立router实例
const router = new VueRouter({
  // 配置路由和组件之间的应用关系
  routes,  // (缩写) 至关于 routes: routes
});

// 4. 导出router对象,而后在main.js中引用
export default router;

这个文件是专门配置路由的,最后将router对象导出后,咱们在项目的main.js中引用便可vue-cli

import Vue from "vue";
import App from "./App.vue";
import router from "./router";

Vue.config.productionTip = false;

new Vue({
  router,  // 在vue实例中添加router对象,就可使用路由了
  render: (h) => h(App),
}).$mount("#app");

 
咱们的2个组件代码AboutHome代码以下:npm

// About.vue
<template>
  <div class="about">
    <h1>About</h1>
  </div>
</template>

<script>
export default {
  name: "About"
}
</script>

<style scoped>
</style>

// Home.vue
<template>
  <div class="home">
    <h1>Home</h1>
  </div>
</template>

<script>

export default {
  name: "Home",
};
</script>

<style scoped>
</style>

最后咱们在App.vue中,写入以下代码:浏览器

<template>
  <div id="app">
    <router-link to="/">首页</router-link>
    <router-link to="/about">关于</router-link>
    <router-view></router-view>
  </div>
</template>

<style lang="scss">
</style>

使用<router-link>来加载连接,而后使用to表示跳转的连接。最终会把<router-link>渲染成<a>标签。
<router-view>是路由的出口,也就是相应url下的代码会被渲染到这个地方来。
 app

HTML5 history模式

可是当咱们启动程序,访问页面的时候,url地址上会出现#
watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
这是由于vue-router 默认 hash 模式 —— 使用 URLhash 来模拟一个完整的 URL,因而当 URL 改变时,页面不会从新加载。
若是不想要很丑的 hash,咱们能够用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须从新加载页面。ide

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

咱们只需在router文件夹下的index.js中添加modehistory便可,以后从新访问,http://localhost:8080/就不会有#号了模块化

注意:history模式还须要后台配置支持。由于咱们的应用是个单页客户端应用,若是后台没有正确的配置,当用户在浏览器直接访问其余url地址就会返回 404,这就很差看了。

因此呢,你要在服务端增长一个覆盖全部状况的候选资源:若是 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。

相关文章
相关标签/搜索