vue 實現路由跳轉
阿新 • • 發佈:2018-11-02
1.前一節已經安裝了vue-router(npm install vue-router --save),現在就來使用一下
1)先在App.vue元件中配置路由出口
<template> <div id="app"> <div class="container"> <app-header></app-header> </div> <div class="container"> <!-- 路由匹配到的元件將渲染在這裡 --> <router-view></router-view> </div> </div> </template>
2) 配置main.js檔案
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import { routes } from './router'
Vue.use(VueRouter);
const router = new VueRouter({
routes,
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
3)配置 router.js檔案
import Home from './components/Home' import Coupon from './components/Marketing/Coupon' import Questionnaire from './components/Marketing/Questionnaire' import Analysis from './components/Marketing/Analysis' export const routes = [ { path: '/', component: Home}, { path: '/coupon', component: Coupon}, { path: '/questionnaire', component: Questionnaire}, { path: '/analysis', component: Analysis}, { path: '*', redirect: '/' } ]
這裡最後一條配置是當訪問的 url 沒有路由與之匹配的話就跳轉到主頁
4) 修改Header.vue 元件
<template> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <router-link class="py-2" to="/"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="d-block mx-auto"><circle cx="12" cy="12" r="10"></circle><line x1="14.31" y1="8" x2="20.05" y2="17.94"></line><line x1="9.69" y1="8" x2="21.17" y2="8"></line><line x1="7.38" y1="12" x2="13.12" y2="2.06"></line><line x1="9.69" y1="16" x2="3.95" y2="6.06"></line><line x1="14.31" y1="16" x2="2.83" y2="16"></line><line x1="16.62" y1="12" x2="10.88" y2="21.94"></line></svg> </router-link> <router-link to="/" class="navbar-brand">主頁</router-link> <ul class="navbar-nav"> <li><router-link to="/coupon" class="nav-link">優惠券管理</router-link></li> <li><router-link to="/questionnaire" class="nav-link">問卷管理</router-link></li> <li><router-link to="/analysis" class="nav-link">資料統計</router-link></li> </ul> </nav> </header> </template>
然後 npm run dev 執行就OK了!
具體配置解釋和更多資訊可以訪問 vue-router 官方文件檢視