import Vue from 'vue'; import App from './App.vue'; //引入公共的scss 注意:建立項目的時候必須用scss import './assets/css/basic.scss'; //請求數據 import VueResource from 'vue-resource'; Vue.use(VueResource); import VueRouter from 'vue-router'; Vue.use(VueRouter); //1.建立組件 import Home from './components/Home.vue'; import News from './components/News.vue'; import Content from './components/Content.vue'; //2.配置路由 注意:名字 const routes = [ { path: '/home', component: Home }, { path: '/news', component: News,name:'news' }, { path: '/content/:aid', component: Content }, /*動態路由*/ { path: '*', redirect: '/home' } /*默認跳轉路由*/ ] //3.實例化VueRouter 注意:名字 const router = new VueRouter({ mode: 'history', /*hash模式改成history*/ routes // (縮寫)至關於 routes: routes }) //四、掛載路由 new Vue({ el: '#app', router, render: h => h(App) }) //5 <router-view></router-view> 放在 App.vue
<template> <!-- 全部的內容要被根節點包含起來 --> <div id="home"> 我是首頁組件 <button @click="goNews()">經過js跳轉到新聞頁面</button> </div> </template> <script> export default{ data(){ return { msg:'我是一個home組件' } }, methods:{ goNews(){ // 注意:官方文檔寫錯了 //第一種跳轉方式 // this.$router.push({ path: 'news' }) // this.$router.push({ path: '/content/495' }); //另外一種跳轉方式 // { path: '/news', component: News,name:'news' }, // router.push({ name: 'news', params: { userId: 123 }}) this.$router.push({ name: 'news'}) } } } </script> <style lang="scss" scoped> </style>