接文集上一篇(可以查看本文文集),已經(jīng)書寫了自己的組件多律,這里主要是路由的控制。
vue.js官方推薦使用官方插件vue-router
首先使用npm安裝此插件
npm install --save vue-router
安裝成功后活鹰,如下圖所示漏策,到目前為止派哲,安裝的版本為
vue-router
在上一篇里建立的test.vue,在這篇中新建一個(gè)test2.vue插件掺喻,無(wú)需在App.vue中調(diào)用芭届。
test2
即打開(kāi)這個(gè)頁(yè)面的時(shí)候應(yīng)該顯示的值為testValue2。
在main.js中調(diào)用和定義路由巢寡,其代碼如下所示喉脖。
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//開(kāi)啟debug模式
Vue.config.debug = true;
// 創(chuàng)建一個(gè)路由器實(shí)例
import test2 from './component/test2.vue'
import test1 from './component/test.vue'
const main={template:'<div>this is main page</div>'}
// 并且配置路由規(guī)則
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/', name: 'main', component: main },
{ path: '/test', name: 'test', component: test1 },
{ path: '/test2', name: 'test2', component: test2 }
]
})
new Vue({
el:'#app',
router,
render: h => h(App)
})
這里定義了一個(gè)常亮main作為打開(kāi)/
目錄時(shí)顯示的文字,并且在路由為相應(yīng)的路由顯示相應(yīng)的組件抑月。
順便將上一節(jié)中的App.vue恢復(fù)树叽,并修改成如下圖所示。
<template>
<div id="app">
<h1>Named Routes</h1>
<p>Current route name: {{ $route.name }}</p>
<ul>
<li><router-link :to="{ name: 'main' }">mian</router-link></li>
<li><router-link :to="{ name: 'test' }">test</router-link></li>
<li><router-link :to="{ name: 'test2' }">test2</router-link></li>
</ul>
<router-view class="view"></router-view>
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {}
},
}
</script>
此時(shí)谦絮,服務(wù)器應(yīng)該自動(dòng)刷新頁(yè)面题诵,顯示效果如下圖所示。
主頁(yè)
test
test2
done