vue 路由传参的基本方式

举例说明

点击父组件的button按钮跳转到子组件中,并携带参数,便于子组件获取数据

父组件:My.vue

<template>
  <div id="my">我的组件
    <button @click="goHome">跳转到首页</button> //方法goHome
  </div>
</template>

父组件:My.vue

export default {
    
    
  name: "my",
  data(){
    
    
    return {
    
    
      id:1000
    }
  },
  mounted() {
    
    
      console.log(this.$route.params);//My的路由地址
  },
  methods: {
    
    
    goHome(){
    
    
      console.log(this.$router);  //My的路由地址
    },
  },
};

1.字符串路径

methods: {
    
    
goHome(){
    
    
      //字符串路径
      this.$router.push("/");
      //或者
      this.$router.push({
    
    path:'/'});
      }
}

需要对应路由配置如下:

{
    
    
    path: '/',
    name: 'Home',
    component: Home
  },

Home.vue 子组件

<template>
  <div class="home">
    首页组件
  </div>
</template>
<script>
export default {
    
    
  name: 'Home',
  mounted() {
    
    
    //获取路由路径get传值
    console.log(this.$route);
  },
}
</script>

输出结果:
在这里插入图片描述
浏览器界面:
点击My跳转到Home组件
在这里插入图片描述

2.以路由名称 跳转带参 params

methods: {
    
     
goHome(){
    
    
 //以路由名称 跳转带参   params
  this.$router.push({
    
    name:'About',params:{
    
    id:10}});}
  }

需要对应路由配置如下:

{
    
    
    path: '/about/:id',
    name: 'About',
    component:About
  },

About.vue 子组件

<template>
  <div class="about">
     关于组件
  </div>
</template>
<script>
export default {
    
    
   name:'about',
   mounted() {
    
    
     //挂载完成获取路由的动态传值
     //this.$router  类似history对象的一个api
     //this.$route 这个api是当前路由的相关匹配参数
     console.log(this.$route);
     console.log(this.$route.params.id);
   },
}
</script>

输出结果:
在这里插入图片描述
浏览器界面:
点击My跳转到About组件
在这里插入图片描述

3. 编程式跳转 get传值 query

methods: {
    
     
goHome(){
    
    
         this.$router.push({
    
    path:'/',query:{
    
    id:1,name:'abc'}});
      // 或者 this.$router.push({
    
    name:"Home",query:{
    
    id:1,name:'abc'}});
  }

需要对应路由配置如下:

 {
    
    
    path: '/',
    name: 'Home',
    component: Home
  },

子组件为Home.vue

<template>
  <div class="home">
    首页组件
  </div>
</template>

<script>
export default {
    
    
  name: 'Home',
  mounted() {
    
    
    //获取路由路径get传值
    console.log(this.$route.query);
    console.log(this.$route);
  },
}
</script>

输出结果:
在这里插入图片描述
浏览器界面:
点击My跳转到Home组件
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_47863547/article/details/115706159
今日推荐