vuejs 實現路由的方式
1. 使用router-link
<script src="vue.js"></script>
<script src="vue-router.js"></script>
<style>
.box {
width: 100px;
height: 100px;
background: green;
margin-right: 20px;
float: left;
}
.router-link-active {
color: red;
}
</style>
</head>
<body>
<div id="div1">
<!-- <router-link class='box btn' to="/a/56">News</router-link> -->
<router-link class='box' :to="{name:'news', params:{id:98}}">news</router-link>
<router-link class='box btn' to="/b">Entertainment</router-link>
<router-link class='box btn' to="/c">Lifetime</router-link>
<router-view></router-view>
內容
</div>
<script>
let router = new VueRouter({
routes: [{
path: '/a/:id',
name: 'news',
component: {
template: '<div>{{$route.params.id}}</div>'
}
},
{
path: '/b',
name: 'entertainment',
component: {
template: '<div>bbb</div>'
}
},
{
path: '/c',
name: 'lifetime',
component: {
template: '<div>ccc</div>'
}
}
]
});
let vm = new Vue({
el: '#div1',
data: {},
router
})
</script>
</body>
2 js方式實現
<script src="vue.js"></script>
<script src="vue-router.js"></script>
</head>
<body>
<div id="div1">
<!-- <router-link class='nav' to="/a/34">新聞</router-link>
<router-link class='nav' to="/b">娛樂</router-link>
<router-link class='nav' to="/c">天氣</router-link> -->
<input type="button" value='頁面1' @click='fn1()'>
<input type="button" value='頁面2' @click='fn2()'>
<input type="button" value='頁面3' @click='fn3()'>
<router-view></router-view>
</div>
<script>
let router = new VueRouter({
routes: [{
path: '/a/:id',
name: 'news',
component: {
template: '<div>{{$route.params.id}}</div>'
}
},
{
path: '/b',
name: 'entertainment',
component: {
template: '<div>bbb</div>'
}
},
{
path: '/c',
name: 'whether',
component: {
template: '<div>ccc</div>'
}
},
]
})
let vm = new Vue({
el: '#div1',
router,
methods: {
fn1() {
//this.$router.push('/a/19');
this.$router.push({
name: 'news',
params: {
id: 12
}
});
},
fn2() {
this.$router.push('/b');
},
fn3() {
this.$router.push('/c');
}
}
})
</script>