1. 程式人生 > 其它 >從零開始學VUE之VueRouter(Vue-router基本使用)

從零開始學VUE之VueRouter(Vue-router基本使用)

使用Vue-router

建立元件

About.vue

<template>
  <div>
    <h2>this is about!</h2>
  </div>
</template>

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

<style scoped>

</style>

Home.vue

<template>
  <div>
    <h2>this is home!</h2>
  </div>
</template>

<script>
export 
default { name: "Home" } </script> <style scoped> </style>

在Index.js中新增對映規則

import Vue from 'vue'
// 匯入路由
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

import home from '../components/Home'
import about from '../components/About'

// Vue載入
Vue.use(Router)

// 傳入路由對映配置 匯出路由例項 export default new Router({ routes: [ // { // path: '/', // name: 'HelloWorld', // component: HelloWorld // }, { path: '/home', name: 'home', component:home }, { path: '/about', name: 'about', component:about }, ] })

在App.vue中新增導航

通過router-view展示

<template>
  <div id="app">
<!--    <img src="./assets/logo.png">-->
<!--    導航連結-->
    <router-link to="/home">主頁</router-link>
    <router-link to="/about">關於</router-link>
<!--    用於展示元件-->
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

效果

點選主頁

點選關於

預設展示首頁

增加index.js的配置

// 在預設的情況下 重定向到主頁
    {
      path: '',
      redirect: "/home"
    },

預設跳轉的uri是使用的hash方式,這樣會留下history歷史記錄,也就是說可以通過瀏覽器的左右箭頭控制前後跳轉,並且路徑中間會有#號

如果不希望存在#,可以設定模式為history

// 設定模式為 history
mode: 'history',

如果不希望存在瀏覽記錄History可以將to 改為replace

可以在 router-link 中新增 replace 屬性

作者:彼岸舞

時間:2021\06\28

內容關於:VUE

本文屬於作者原創,未經允許,禁止轉發