vue-router路由跳转

【一】安装

cnpm install -S vue-router

【二】app.vue

 <router-link to=""></router-link>

【三】路由跳转(不携带数据)

【1】js跳转三种方式

<button @click="handleTo">js跳转--跳转到about页面</button>

methods: {
    handleTo(){
    console.log(this.$router)
      写路径
      this.$router.push('/about')
      写对象
      this.$router.push({
        name:'about'
      })
      this.$router.push({
        path:'/about'
      })

    }
  }

【2】标签跳转三种方式

<router-link to="/about">
      <button>标签跳转--跳转到about页面</button>
</router-link>

<router-link :to="{name:'about'}">
      <button>标签跳转--跳转到about页面</button>
</router-link>

<router-link :to="{path:'about'}">
      <button>标签跳转--跳转到about页面</button>
</router-link>

【四】路由跳转(携带数据)

【1】跳转

-js跳转
this.$router.push(路径)
this.$router.push(对象)
    -this.$router.push({name:'路由别名'})
    -this.$router.push({path:'路径'})   
-组件跳转
<router-link to="/about">
    <router-link :to="{name:'路由别名'}">
        <router-link :to="{path:'路径'}">

【2】路由跳转,携带数据(组件跳转和js跳转)

【1】第一种

  • /about?name=数据
  • /about?name=hope&age=24

image-20240506152204537

  <div class="home">
    <router-link to="/about?name=hope">
      <button>跳转到about界面携带数据1</button>
    </router-link>
    <router-link :to="{name:'about', query:{name:'hope',age:24}}">
      <button>跳转到about界面携带数据2</button>
    </router-link>
  </div>
或者
 <button @click="handleChange1">js跳转1</button>
<button @click="handleChange2">js跳转2</button>
export default {
  name: 'HomeView',
  components: {},
  methods: {
    handleChange1() {
      this.$router.push('/about?name=hope&age=19')
    },
    handleChange2() {
      this.$router.push({name: 'about', query: {name: 'hope', age: 24}})
    }
  }
}
<template>
  <div class="About">
    <h1>姓名: {{name}}</h1>
    <h1>年龄: {{age}}</h1>
  </div>
</template>

<script>
export default {
  name: 'AboutView',
  data(){
    return{
      name:'',
      age:''
    }
  },
  created() {
    console.log(this.$route)
    this.name=this.$route.query.name
    this.age=this.$route.query.age
  },
  components: {

  }
}
</script>

【2】第二种

  • /about/数据/
  • /about66/detail
<template>
  <div class="home">
    <router-link to="/about/88">
      <button>跳转到about界面携带数据1</button>
    </router-link>
    <router-link :to="{name:'about', params:{id:66}}">
      <button>跳转到about界面携带数据2</button>
    </router-link>
    <hr>
    <button @click="handleChange1">js跳转1</button>
    <button @click="handleChange2">js跳转2</button>
    <hr>
  </div>
</template>

<script>

export default {
  name: 'HomeView',
  components: {},
  methods: {
    handleChange1() {
      // this.$router.push('/about?name=hope&age=19')
      this.$router.push('/about/qq')
    },
    handleChange2() {
      this.$router.push({name: 'about', params: {id: 66}})
    }
  }
}
</script>
  created() {
    console.log(this.$route)
    this.id=this.$route.params.id
  },
posted @ 2024-05-08 17:35  -半城烟雨  阅读(27)  评论(0)    收藏  举报