zoukankan      html  css  js  c++  java
  • Vue Router路由组件传参

    在组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。

    使用 props 将组件和路由解耦

    //router.js
    import Vue from 'vue'
    import Router from 'vue-router'
    import HelloWorld from '@/components/HelloWorld'
    import Test from '@/components/test'
    Vue.use(Router)
    
    export default new Router({
      routes: [
        {
          path: '/',
          name: 'HelloWorld',
          component: HelloWorld
        },
        {
        //动态路由参数 以冒号开头 path: '/home/:id', name: 'test', component: Test, props: true // 此时params就是组件的props }
    ] })

    一个“路径参数”使用冒号 : 标记。当匹配到一个路由时,参数值会被设置到 this.$route.params,可以在每个组件内使用

    跳转链接:

    <router-link :to="{name:'test',params:{id:123}}" >测试</router-link>

    必须使用params属性传递参数,使用query传递还是会以查询串的形式拼接在地址栏末尾。

    注意:这里必须要使用name跳转路由,如果使用path,params会被忽略,官网有说明

    点击跳转链接url如下图:

     在test组件中用props属性接收传递的参数:

    export default {
      name: 'test',
      props: ['id'],
      created () {
        console.log('params', this.$route.params)
        console.log('id', this.id)
      },
    }  

    控制台如下:

      

  • 相关阅读:
    迭代器模式 -- 大话设计模式
    组合模式 -- 大话设计模式
    备忘录模式 -- 大话设计模式
    totalcmd简单教程--help详解
    Listary Primary
    Cygwin Primary
    Google calendar
    极点郑码标点符号
    Totalcmd 简单教程
    Foobar 简单教程
  • 原文地址:https://www.cnblogs.com/wangyunhui/p/14583571.html
Copyright © 2011-2022 走看看