https://router.vuejs.org/ vue路由配置: 1.安裝 npm install vue-router --save / cnpm install vue-router --save 二、引入並 Vue.use(VueRouter) (main.js) import VueRouter from 'vue-router' Vue.use(VueRouter) 三、配置路由 一、建立組件 引入組件 二、定義路由 (建議複製s) const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar }, { path: '*', redirect: '/home' } /*默認跳轉路由*/ ] 三、實例化VueRouter const router = new VueRouter({ routes // (縮寫)至關於 routes: routes }) 四、掛載 new Vue({ el: '#app', router, render: h => h(App) }) 5 、根組件的模板裏面放上這句話 <router-view></router-view> 六、路由跳轉 <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link>
main.jscss
import Vue from 'vue'; import App from './App.vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); //1.建立組件 import Home from './components/Home.vue'; import News from './components/News.vue'; //2.配置路由 注意:名字 const routes = [ { path: '/home', component: Home }, { path: '/news', component: News }, { path: '*', redirect: '/home' } /*默認跳轉路由*/ ] //3.實例化VueRouter 注意:名字 const router = new VueRouter({ routes // (縮寫)至關於 routes: routes }) //四、掛載路由 new Vue({ el: '#app', router, render: h => h(App) }) //5 <router-view></router-view> 放在 App.vue
<template> <div id="app"> <router-link to="/home">首頁</router-link> <router-link to="/news">新聞</router-link> <hr> <router-view></router-view> </div> </template> <script> export default { data () { return { msg:'你好vue' } } } </script> <style lang="scss"> </style>
<template> <!-- 全部的內容要被根節點包含起來 --> <div id="home"> 我是首頁組件 </div> </template> <script> export default{ data(){ return { msg:'我是一個home組件' } } } </script> <style lang="scss" scoped> </style>
<template> <div id="news"> 我是新聞組件 </div> </template> <script> export default{ data(){ return { msg:'我是一個新聞組件' } } } </script> <style lang="scss" scoped> </style>