簡單例子
通過路由只能實現簡單的跳轉,但是跳轉時我們常常需要做一些判斷 需要用到編程性導航
簡單帶參數例子
<template>
<div id="app">
<div id="nav">
<br>
<router-link to="/user/5/profile">5號檔案</router-link>
<br><br>
<router-link to="/user/5/posts">5號崗位</router-link>
<br><br>
<button @click="goUser(5)">goUser</button>
</div>
<router-view/>
</div>
</template>
<script>
export default {
methods:{
goUser(tempid){
this.$router.push({
name : `User`,
params : {
id:tempid
}
})
},
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
}
#nav a {
font-weight: bold;
color: #2c3e50;
}
#nav a.router-link-exact-active {
color: #42b983;
}
</style>
命名路由
簡單例子
<router-link :to="{name : 'User',params : {id:5}}">使用命名路由跳轉</router-link>
命名視圖
通過命名視圖來區別不同視圖區,使得編程更加容易
簡單例子:
編寫一個footer和sidebar組件,在然后網頁跳轉時都顯示該組件
<template>
<h3>這是sidebar組件</h3>
</template>
<script>
export default {
name: "sidebar"
}
</script>
<style scoped>
</style>
footer同理
在index.js配置路由信息里使用compents
{
path: '/',//鏈接地址
name: 'Home',//別名
components: {
default : Home,
sidebar : sidebar,//前面是視圖名 后面是導入的組件名
footer : footer
}
},
在app.vue里使用3次組件視圖 同時將其中的兩個視圖定義名字
<router-view name="sidebar"></router-view>
<router-view/>
<router-view name="footer"></router-view>
效果