vue动态传参

博客介绍了Vue中路由传参的方法。方法一是传入多个参数,在router.js中使用vue - router,在path里反斜杠后加冒号表示路由参数,再到对应组件接收;还提及了方法二的父组件、子组件js结构及方法三的标签相关内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:

传入多个参时:

<router-link to='/tr/uid/pid'>查看</router-link>

然后router.js:

import Vue from 'vue'

import Router from 'vue-router'

import tr from '@/components/tr.vue'

import tab from '@/components/tab.vue'

Vue.use(Router)

export default new Router({

routes:  {

  path:'/tr/:uid/:pid',

  name: 'tr',

  component:tr

  }

})

需要在router.js 中使用vue-router,具体是在path:’/tr/:uid/:pid’, 反斜杠后加冒号,意思是后面就是路由的参数。

然后去对应tr.vue组件中接受这个路由参数:

通过实例的this.$route.params,可访问这个key-value对象,

 我们给请求路由赋个值看看:

<router-link to='/tr/15/122'>查看</router-link>

打印如下Object {uid: "15", pid: "122"} 

方法二:

父组件结构:

<template>
  <div style="width: 200px;margin: 0 auto">
    <div v-for="(items,index) in subjects" :key="index" v-if="index<4">
      <div style="width: 200px;height: 220px;">
          <div style="width: 200px;height: 20px;">{{items.title}}</div>
          <img :src="items.images.large" alt="" style="width: 200px;height: 200px;">
      </div>
      <router-link :to="{name:'child',params:{id:items.id}}">
        <button style="margin: 10px 0 10px 0;cursor: pointer">查看详情</button>
      </router-link>
    </div>
    <router-view></router-view>
  </div>
</template>

js:

export default {
  name: 'HelloWorld',
  data () {
    return {
      subjects: ''
    }
  },
  created () {
    this.axios.get('api/movie/in_theaters')
      .then((res) => {
        console.log(res)
        this.subjects = res.data.subjects
      })
  }
}

router路由index.js:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import route from '@/components/dong/route'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/child/:id',
      name: 'child',
      component: route
    },
  ]
})

子组件js:

<script>
    export default {
      name: "route",
      data () {
        return {
          id: '',
          msg: ''
        }
      },
      created () {
        this.id=this.$route.params.id;
        this.axios.get('api/movie/subject/'+this.id)
          .then((res)=>{
            console.log(res);
            this.msg=res.data
          })
      }
    }
</script>

方法三:

1.标签

<li v-for=" el in hotLins" >
    <router-link :to="{path:‘details‘,query: {id:el.tog_line_id}}">
        <img :src="el.image_list[0]">
        <h3>{{el.tourism_name}} {{el.tog_line_id}}</h3>
        <p>{{el.address}}</p>
    </router-link>
</li>
2.在组件中,需要传动态参数时,可以如上例子 
<router-link :to="{path:‘details‘,query: {id:el.tog_line_id}}">

3.query中的参数id就是要传的参数,在组件中获取的方法为:
created: function() {
    var id = this.$route.query.id;
    this.getData(id);
 },
4.如上述,this.$route.query.id就可以获取该参数,也可以通过,this.$root.id = id;传给父组件,父组件中通过
// 根组件构造器
    var vm = Vue.extend({
      router: router,
      data: function() {
        return {
          id: ‘11484‘ //城会玩明细id
        }
      }
    })
5.定义data中的id,然后子组件中用props传递参数
props: {
        id: {
          type: String,
          required: true
        }
      },
6.router-view中,传递该参数:
<router-view :id="id" :order-info="orderInfo">
</router-view>

 

 

<think>嗯,用户想了解如何在 Vue 中实现动态组件的参数传递,特别是需要示例教程。首先,我需要回顾一下 Vue动态组件相关知识。动态组件主要是通过 `<component :is="currentComponent">` 这样的语法来切换不同的组件。关于传参,我记得可以通过props传递,但动态组件的情况下可能需要不同的方式。 用户提供的引用中有提到动态组件的传参,比如引用[1]中的例子,通过属性绑定传递someProp给动态组件。这里应该是在使用动态组件时,像普通组件一样绑定属性。例如,在父组件中,为动态组件设置属性,然后在子组件中用props接收。这应该是一个基本方法。 另外,引用[3]和[4]提到了使用provide/inject或者Vuex来进行跨组件传参。不过用户的问题更偏向于动态组件本身的传参,可能更直接的是使用props。但有时候动态组件的类型不确定,可能需要不同的props,这时候可能需要其他方法,比如通过对象动态绑定属性,或者使用v-bind来传递对象的所有属性。 还有,引用[2]提到通过parent或children访问实例,但这种方法可能不太推荐,因为Vue更倾向于单向数据流,直接操作实例可能引起维护问题。不过用户可能需要了解不同的方法,比如使用ref来获取子组件实例,然后直接调用方法或修改数据,但需要注意响应式的问题。 可能还需要考虑动态组件在切换时的状态保持,比如使用`<keep-alive>`来缓存组件实例,这样传递的参数在切换时不会被重置。这点可能在示例中需要提到。 需要确保示例覆盖不同的传参方式:props直接传递、动态绑定不同属性、使用provide/inject,以及使用事件传递数据回来。同时,可能还需要注意Vue2和Vue3的语法差异,比如在Vue3中使用setup函数和组合式API的情况。 现在需要组织这些知识点,给出清晰的步骤和示例代码。首先介绍基本props传参,然后动态属性绑定,接着事件通信,最后高级方法如provide/inject。同时,提醒用户在不同场景下的选择,比如简单场景用props,复杂跨层级用provide/inject或Vuex。 需要检查示例代码的正确性,比如在动态组件中使用v-bind传递对象,确保子组件正确接收props。另外,在事件部分,父组件监听子组件事件,并在方法中处理数据。还要注意在Vue3中,使用setup语法时props的声明方式,以及emits的配置。 最后,总结不同方法的适用场景,帮助用户根据具体情况选择合适的方式。可能还需要提到使用keep-alive来保持状态,避免重复传参的问题。确保回答结构清晰,步骤明确,示例代码正确,符合用户的需求。</think>### Vue动态组件传参方法详解 动态组件传参主要通过以下四种方式实现,根据Vue官方推荐模式结合示例说明: #### 一、基础props传参(推荐) ```html <!-- 父组件 --> <template> <component :is="currentComponent" :msg="parentMsg"></component> </template> <script> import ComponentA from './ComponentA.vue' import ComponentB from './ComponentB.vue' export default { components: { ComponentA, ComponentB }, data() { return { currentComponent: 'ComponentA', parentMsg: '来自父组件的数据' } } } </script> <!-- 子组件ComponentA.vue --> <template> <div>{{ msg }}</div> </template> <script> export default { props: { msg: String // 明确声明接收的prop } } </script> ``` 特点:通过$:is$绑定的组件会自动继承父组件传递的props,需在子组件显式声明props属性[^1] #### 二、动态属性绑定(多参数场景) ```html <!-- 父组件 --> <component :is="currentTab" v-bind="currentProps" @custom-event="handleEvent"> </component> <script> data() { return { currentTab: 'UserProfile', currentProps: { userId: 123, userName: '张三' } } } </script> <!-- 子组件UserProfile.vue --> <script> export default { props: ['userId', 'userName'] } </script> ``` 优势:通过$v-bind$指令批量传递对象属性,适合需要传递多个参数的场景[^4] #### 三、事件通信(子传父) ```html <!-- 子组件 --> <template> <button @click="sendData">提交</button> </template> <script> export default { methods: { sendData() { this.$emit('update-data', { value: this.formData }) } } } </script> <!-- 父组件 --> <component :is="activeComponent" @update-data="handleUpdate"></component> <script> methods: { handleUpdate(payload) { console.log('接收子组件数据:', payload) } } </script> ``` 注意:事件名建议使用kebab-case格式,父组件通过@event-name接收[^2] #### 四、高级传参方式 1. **Provide/Inject(跨层级)** ```javascript // 父组件 export default { provide() { return { configData: reactive({ theme: 'dark', apiUrl: 'https://api.example.com' }) } } } // 子孙组件 export default { inject: ['configData'] } ``` 2. **Vuex状态管理** ```javascript // store.js export default new Vuex.Store({ state: { sharedData: '全局数据' } }) // 动态组件内使用 computed: { sharedData() { return this.$store.state.sharedData } } ``` 适用场景:当需要跨多级组件传参或全局状态管理时推荐使用 #### 最佳实践建议 1. 简单父子传参优先使用props/events 2. 深层嵌套组件使用provide/inject 3. 大型应用采用Vuex/Pinia状态管理 4. 动态组件切换建议配合`<keep-alive>`保持状态: ```html <keep-alive> <component :is="currentComponent"></component> </keep-alive> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值