编程式导航

编程式导航是通过js进行导航驱动,之前声明式是通过点击元素进行跳转

基本使用

 1 <template>
 2     <div>
 3         <!--显示区域-->
 4         <router-view></router-view>
 5         <div class="box">
 6             <div class="left" @click="toHome">
 7                 首页
 8             </div>
 9             <div class="right" @click="toSport">
10                 体育
11             </div>
12         </div>
13 
14     </div>
15 </template>
16 
17 <script>
18     export default {
19        methods:{
20            toHome(){
21                this.$router.push("/home")
22            },
23             toSport(){
24                this.$router.push("/sport")
25            }
26        }
27     }
28 </script>
29 
30 <style scoped>
31 .box{
32     display: flex;
33 }
34 .box  .left{
35     flex:1;
36     line-height:40px;
37     background: orange;
38     color: white;
39     text-align: center;
40 }
41 .box  .right{
42      flex:1;
43     line-height:40px;
44     background: skyblue;
45     color: white;
46     text-align: center;
47 }
48 </style>

 

 

 

$router是vue-router提供的函数钩子,内置了所有的关于路由跳转的方法

如果配置了vue-router就可以使用$router方法,不用再配置Vue.prototype.***

除了可以跳转之外和声明式类似的是也可以进行参数挂载

 

 1  toHome(){
 2                let obj={
 3                    path:'/home',
 4                    query:{
 5                        a:1,b:2,c:3
 6                    }
 7                }
 8                this.$router.push(obj)
 9            },
10             toSport

如果是name和params一组

1 let obj = {
2     name: 'home',
3     params: {
4         a: 1,
5         b: 2,
6         c: 3
7     }
8 }
9 this.$router.push(obj)

 

 

 

 

我们之前说过name和path之间的区别直观的体现在路由上,一个挂载参数,一个不挂载参数

除了push还有一种跳转方式,是replace,和push的区别一个会有历史记录,一个没有历史记录

1   toHome(){
2                let obj={
3                    name:'/home',
4                    parmas:{
5                        a:1,b:2,c:3
6                    }
7                }
8                this.$router.replace(obj)
9            },

 

posted @ 2021-09-23 17:48  keyeking  阅读(798)  评论(0编辑  收藏  举报