编程式路由导航小例子

作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活

知识点

//$router的两个API
this.$router.push({
    name:'xiangqing',
        params:{
            id:xxx, //可以传参
            title:xxx //可以传参
        }
})

this.$router.replace({
    name:'xiangqing',
        params:{
            id:xxx, //可以传参
            title:xxx //可以传参
        }
})

this.$router.forward() //前进
this.$router.back() //后退
this.$router.go() //可前进也可后退,看正负数

举个小例子

实现效果

分析

  • 首先要判断输入的文字内容是否是正确的暗号,通过v-model来绑定里面的数据
  • 给按钮绑定一个事件函数,函数接收输入的内容作为参数
  • 函数里面做判断,判断后通过$router.push跳转到哪个路径显示对应的组件
  • 销毁按钮通过绑定一个事件函数,里面通过this.$router.go()来返回到上一步

完整代码示例

//路由器代码
//该文件专门用于创建整个应用的路由器

//引入VueRouter
import VueRouter from "vue-router"

// 引入路由组件
import Message from '../pages/Message'
import Secret from '../pages/Secret'

// 创建一个路由器
const router = new VueRouter({
    routes: [{
        name: 'xiaoxi',
        path: '/message',
        component: Message
    }, {
        name: 'mimi',
        path: '/secret',
        component: Secret
    }]
})

//暴露路由器
export default router
//App组件代码
<template>
  <div class="box">
    <h1>情报驿站</h1>
    天王盖地虎,<input type="text"  v-model="m"  placeholder="请输入暗号"><button @click="sure(m)">确定</button><br>
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    name: 'App',
    data:{
    m:''
    },
    methods:{
      sure(m){

        if(m==='我是二百五'){
          this.$router.push({
          name:'mimi'
        })
        
        }else if(m==='宝塔镇河妖'){
          this.$router.push({
          name:'xiaoxi'
          })
        }else{
          alert('请输入正确暗号')
        }
        this.m=''
      }
    }
  }
</script>

<style scoped>
  .box{
    width: 350px;
    height: 200px;
    background-color: bisque;
    padding: 40px;
    text-align:center;
    margin: 0 auto;
  }
  button{
    margin-left: 20px;
  }
</style>
//Message组件代码
<template>
<div>
     <h3>两天后黄金价格会跌</h3>
   <Destroy/>
</div>
</template>

<script>
import Destroy from './Destroy.vue'
    export default {
  components: { Destroy },
        name:'Message'
    }
</script>

<style scoped>
h3{
  background-color: blueviolet;
}
</style>
//Secret组件代码
<template>
  <div>
    <h3>有内鬼,终止交易!!!</h3>
    <Destroy/>
  </div>
</template>

<script>
import Destroy from './Destroy.vue'
    export default {
  components: { Destroy },
        name:'Secret', 
    }
</script>

<style scoped>
h3{
  background-color: black;
  color: aqua;
}
</style>
//Destroy组件代码
<template>
   <button @click="destroySecret">销毁</button>
</template>

<script>
    export default {
        name:'Destroy',
        methods:{
            destroySecret(){
                this.$router.go(-1)
            }
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/m0_61843874/article/details/124754762
今日推荐