由于vue-router在vue1.0和2.0中写法不一样,这里我们只看2.0版本的写法。
首先看一下我们最后的结果:
点击上面三个标签,在下面显示对应的内容。
首先引入vue-router,在package.json中的dependencies中添加vue-router的版本,如图:
还需要新建3个组件来做vue-router的测试,goods、ratings、seller对应上面的商品、评论、商家的标签,如图:
主页面App.vue当中我们把3个标签写上,
App.vue
<template>
<div>
<mainHeader></mainHeader>
<div class="tab">
<div class="tab-item">
<router-link to="/goods">商品</router-link>
</div>
<div class="tab-item">
<router-link to="/ratings">评论</router-link>
</div>
<div class="tab-item">
<router-link to="/seller">商家</router-link>
</div>
</div>
<div class="view">
<router-view></router-view>
</div>
</div>
</template>
<script>
import mainHead from './components/header/main_header';
export default {
name: 'app',
data: function () {
return {
};
},
components: {
mainHeader: mainHead
},
methods: {
},
mounted: function () {
this.$nextTick(function () {
});
}
};
</script>
<style>
.tab{
display: flex;
width: 100%;
height: 40px;
line-height: 40px;
}
.tab-item{
flex: 1;
text-align: center;
}
.tab-item>a{
display: block;
}
.router-link-active{
background: #11aa11;
color: #ffffff;
}
</style>
主要是在div.class=tab中写3个标签,
div.class=view中加上<router-view>,表示点击标签对应的页面显示的位置
在main.js中引入vue-router并使用
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'; // 引入vue
import App from './App'; // 引入src目录下的App.vue
import VueRouter from 'vue-router'; // 引入vue-router
import goods from './components/goods/goods'; // 引入商品组件
import ratings from './components/ratings/ratings';
import seller from './components/seller/seller';
Vue.config.productionTip = false; // 来关闭生产模式下给出的提示
Vue.use(VueRouter); // 使用vue-router
const routes = [ // 定义vue-router的路径和对应的组件,注意是component 不是components
{
path: '/goods', component: goods
},
{
path: '/ratings', component: ratings
},
{
path: '/seller', component: seller
}
];
let router = new VueRouter({ // 新建router 并传入routes
routes
});
/* eslint-disable no-new */
new Vue({
el: '#app', // App.vue中的id=app的div
router, // 注入路由
template: '<App/>', // 这里是把'./App'的内容加到这个模板中
components: { App } // 这里的App等于App: App ,名称要和模板名称一样,上面的template中写的App,这里也要是App
});
到这里一个简单的vue-router就写好了.
如果需要默认指定vue-router初始页面,需要这样写
const routes = [ // 定义vue-router的路径和对应的组件,注意是component 不是components
{
path: '/',
redirect: '/goods' // 指定默认页面
},
{
path: '/goods',
component: goods
},
{
path: '/ratings',
component: ratings
},
{
path: '/seller',
component: seller
}
];
如果你还想监听路由变化,可以用watch监听
watch: {
'$route': function (to, from, next) {
console.log(to);
}
}