vue 路由传参 编程式路由导航

(2)路由传参

 ①query传参

  

this.$router.push({name:'home',query: {id:'1'}})

this.$router.push({path:'/home',query: {id:'1'}})

// html 取参  $route.query.id

// script 取参  this.$route.query.id

 ②params传参

this.$router.push({name:'home',params: {id:'1'}})  // 只能用 name

// 路由配置 path: "/home/:id" 或者 path: "/home:id" ,

// 不配置path ,第一次可请求,刷新页面id会消失

// 配置path,刷新页面id会保留

  

// html 取参  $route.params.id

// script 取参  this.$route.params.id

 ③query和params区别

query类似 get, 跳转之后页面 url后面会拼接参数,类似?id=1, 非重要性的可以这样传, 密码之类还是用params,刷新页面id还在

  params类似 post, 跳转之后页面 url后面不会拼接参数 , 但是刷新页面id 会消失

3.router-link和router.push实现跳转的原理

router-link

默认会渲染为 a 标签. 可以通过 tag 属性修改为其他标签 自动为 a 标签添加 click 事件. 然后执行 $router.push() 实现跳转

$router.push 根据路由配置的 mode 确定使用 HTML5History 还是 HashHistory 实现跳转  

HTML5History : 调用   window.history.pushState() 跳转

HashHistory : 调用  HashHistory.push() 跳转

那么二者到底有什么区别呢?

mode:'hash' ,   多了 “ # ”

http://localhost:8080/#/hello

mode:'history'

http://localhost:8080/hello

router index.js


{
    // 参数 用 : 代表,  ?代表可选
    path: '/product/:type?',
    props: true,
    name: 'Product',
    component: () => import('../views/Product.vue'),
  },
              <router-link

                :class="{                         顶部导航 当前路由高亮
                  'router-link-exact-active': $route.name == 'Product',
                }"
                to="/product"
                >产品中心<span class="icon_pd"></span
              ></router-link>
              <div class="pd_dropdown">
                <router-link to="/product/1">净美仕净化器</router-link>
                <router-link to="/product/2">净美仕滤网</router-link>
              </div>

    <div class="main container">
      <div class="pl_header">
下边路由高亮
        <router-link to="/product/1" :class="{ cur: type == 1 }"
          >净美仕净化器</router-link
        >
        <router-link to="/product/2" :class="{ cur: type == 2 }"
          >净美仕滤网</router-link
        >
      </div>
export default {
  computed: {
    ...mapState(["imgURL"]),
  },
  // 属性的复杂写法: 可以声明默认值, 应对可选传参
  // props: ['type'], //简化写法
  props: {
    // 属性名:{详细的配置}
    type: {
      // 通过路径传递的参数, 都是字符串类型
      type: String, //类型: String是数字类型
      default: "1", //默认值: '1',  如果没传, 则默认是1
    },
  },
  mounted() {
    this.getData();
  },
  data() {
    return {
      data: null,
    };
  },
  methods: {
    getData(page = 1) {
      // type: 可选传递, 没有传递则为 undefined, 默认值为1
      // 因为 在props中, 指定了默认值, 所以此处不需要再判断
      // const type = this.type ?? 1 // ?? 左侧值是false 则用右侧值
      const url = `product_select.php?pageNum=${page}&type=${this.type}`;

      this.axios.get(url).then((res) => {
        console.log(res);
        this.data = res.data;
      });
    },
  },
  // 监听到路由变化时, 重新发请求
  watch: {
    $route(newValue, oldValue) {
      this.getData();
    },
  },
};

路由qurey传参 

 命名路由

 

  <!-- to 的字符串写法 -->
    <!-- <li v-for="i in msgList" :key="i.id"><router-link
     :to='`/pathName/p/detail?id=${i.id}&tiltle=${i.title}`'>
     {{i.title}}
     </router-link></li> -->

        <li v-for="i in msgList" :key="i.id"><router-link 
        :to="{
         // path:'/pathName/p/detail', path路径切跳转
            name:'Detail',  路由名字跳
            query:{
              id:i.id,
              title:i.title
            }
       }"
        >{{i.title}}</router-link></li>


取值 <li>消息编号:{{$route.query.id}}--{{$route.query.title}}</li>

嵌套路由

import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '../views/Login.vue'
import About from '../views/About.vue'
Vue.use(VueRouter)

const routes = [

  {
    path: '/pathName',
    name: 'routeName',
    component: () => import('../views/pathName.vue'),
    children: [
      {
        path: 'p',
        component: () => import('../views/News.vue'),
        children:[
          {
            path:'detail',
            name:'Detail',
            component: () => import('../views/Detail.vue'),
          }
        ],
      },
      {
        path: 'm',
        component: () => import('../views/Msg.vue'),
        children:[
          {
            path: 'b',
            name: 'routeName',
            component: () => import('../views/MsgChildren.vue'),
          },
        ]
      },
    ]
  },

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

  // { path: '/', redirect: '/login' },
  // {
  //   path: '/login',
  //   name: 'Login',
  //   component: Login
  // },
  // {
  //   path: '/home',
  //   name: 'Home',
  //      component: () => import('../views/Home.vue'),
  //   redirect: '/welcome',
  //   children: [{
  //     path: '/welcome',
  //     name: 'Welcome',
  //     component: () => import("../views/Welcome.vue"),
  //   },
  //   {
  //     path: '/users',
  //     name: 'Users',
  //     component: () => import("../components/user/users.vue"),
  //   },
  //   ]
  // },



]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


//路由导航守卫
// router.beforeEach((to, form, next) => {
// if (to.path === '/login') { next() }
// 获取token
// const tokenStr = window.sessionStorage.getItem('token')
// if (!tokenStr) {
//   next('/login')
// }
//   next()
// })

export default router

params路由

{
    path: '/pathName',
    name: 'routeName',
    component: () => import('../views/pathName.vue'),
    children: [
      {
        path: 'p',
        component: () => import('../views/News.vue'),
        children:[
          {
            path:'detail/:id/:title?',
            name:'Detail',
            component: () => import('../views/Detail.vue'),
          }
        ],
      },
      {
        path: 'm',
        component: () => import('../views/Msg.vue'),
        children:[
          {
            path: 'b',
            name: 'routeName',
            component: () => import('../views/MsgChildren.vue'),
          },
        ]
      },
    ]
  },
params传参
  <ul>
   <ul>
   <!-- to 的字符串写法 -->
    <li v-for="i in msgList" :key="i.id"><router-link
     :to='`/pathName/p/detail/${i.id}/${i.title}`'>
     {{i.title}}
     </router-link></li>
  </ul>
        <li v-for="i in msgList" :key="i.id"><router-link 
        :to="{
         // path:'/pathName/p/detail',  params路径传无效 不配置path 参数丢失
           name:'Detail',
            params:{
              id:i.id,
              title:i.title
            }
       }"
        >{{i.title}}</router-link></li>
  </ul>

  路由开启porps

 路由开启porps

 {
            path:'detail/:id/:title?',
            name:'Detail',
            component: () => import('../views/Detail.vue'),

            props({qurey:{id,title}}){ //对象解构
               return {id,title}
             }
            
            props($route){ //对象解构
              return {id:$route.params.id,
                title:$route.params.title}
            }

           props({params}){ //对象解构
              return {id:params.id,
                title:params.title}
            }
           props({params:{id,title}}){ //对象解构
              return {id, title}
               
            }
          }

***************************************pages页面*******************
<template>
  <div>
   <!-- <li>消息编号:???</li> -->
     <h1>{{id}}</h1>
     <h1>{{title}}</h1>
  </div>
</template>


 export default {
    name:'Detail',
    props:['id','title'],
    mounted () {
      console.log(this.$route)
    },
  }

 <router-link> replace 属性  替换    :replace='true'  简写replace   

 编程式路由导航

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值