基於vue-cli的vue專案之路由1--最基本的使用
阿新 • • 發佈:2019-02-08
程式碼如下,下面是嘴簡單的基礎搭配:
1.第一個子頁面 ./components/hello.vue <template> <div class="hello"> <h1>這個是hello頁面</h1> <h2></h2> </div> </template> <script> export default { name: 'hello', data() { return { msg: 'this is the hello頁面' } }, props: ['logo'] } </script> 2.第二個子頁面 ./components/foo.vue <template> <div class="hello"> <h1>這個是foo頁面</h1> <h2></h2> </div> </template> <script> export default { name: 'hello', data() { return { msg: '這個是foo.vue頁面' } }, props: ['logo'] } </script> 3.配置router的index檔案 ./src/router/index//路由的配置檔案使用use方法, import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const router = new VueRouter({ routes: [{ path: '/hello', component: require('../components/Hello.vue') }, { path: '/foo', component: require('../components/foo.vue') }, { path: '*', redirect: '/hello' },//配置預設頁面路徑 ] }) export default router; 4.配置app.vue ./src/App.vue//配置vue的主介面。使用router-view以及router-link <template> <div id="app"> <!-- <hello></hello> --> <div class="nav"> <!-- 使用 router-link 元件來導航. --> <!-- 通過傳入 `to` 屬性指定連結. --> <!-- <router-link> 預設會被渲染成一個 `<a>` 標籤 --> <ul> <li> <router-link to="/hello">hello</router-link> </li> <li> <router-link to="/foo">foo</router-link> </li> </ul> </div> <div class="main"> <router-view ></router-view> </div> </div> </template> <script> export default { name: 'app', components: {} } </script> <style> body { background-color: #f8f8ff; font-family: 'Avenir', Helvetica, Arial, sans-serif; color: #2c3e50; } .nav { position: fixed; width: 108px; left: 40px; } .nav ul { list-style: none; margin: 0; padding: 0; } .nav ul li { width: 108px; height: 48px; line-height: 48px; border: 1px solid #dadada; text-align: center; } .nav ul li a { text-decoration: none; } .main { height: 400px; margin-left: 180px; margin-right: 25px; } </style> 5.配置main.js// ./src/main.js//配置基礎的檔案路徑,以及使用路由 // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import VueRouter from 'vue-router' import router from './router' Vue.use(VueRouter) new Vue({ el: '#app', router, render: h => h(App) })
執行效果是這樣的: