2019-12-09Vue-cli3如何配置添加路由

Vue-cli3新建項目後相比Vue-cli2少了不少東西,須要本身來安裝使用路由。步驟以下:

安裝路由vue

npm install vue-router

建立router.js與mian.js同級vue-router

router.js中的內容爲npm

import Vue from 'vue'
import Router from 'vue-router'
 
//組件模塊
import Home from './pages/home'
import A from './components/a'
 
Vue.use(Router)
 
export default new Router({
  routes: [
    { path: '/', name: 'home', component: Home },
    { path: '/home', name: 'Home', component: Home },
    { path: '/a',  name: 'A', component: A},
  ]
})

在main.js中添加以下內容app

重要:必定要在App.vue加 <router-view />標籤

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

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

<style>
</style>

就能夠開始使用路由了,在須要使用路由的地方加入如下內容this

<router-link to="/">主頁</router-link>     //切換到指定的組件
<router-link to="/main">主頁</router-link>
<router-link to="/admin">管理頁</router-link>
<router-view/>  //組件顯示的地方

也可經過事件的方法來使用路由spa

methods:{
  toMain() {
    this.$router.push('./main');  //跳轉到指定組件
  },
 
  //使用路由返回上一級
  goBack() {
    window.history.length > 1 ? this.$router.go(-1) : this.$router.push("/");
  },
}
相關文章
相關標籤/搜索