Vue 组件多级继承、继承全部属性

本文介绍了一种在Vue.js中实现多级组件属性和方法传递的简便方法,即使用v-bind=$attrs和v-on=$listeners。通过示例展示了如何在不同层级的组件之间传递未被props明确接收的数据和事件。

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

核心方法

在B组件中添加v-bind="$attrs"v-on="$listeners"两个属性即可`

A 组件中:
<B v-bind="$attrs" v-on="$listeners>
</B>

这样在A中就能使用B的属性和绑定的方法了

如果想详细理解,请继续阅读

一、关于组件之间的通信

组件之间相互传递数据、方法,就可以理解为组件之间的通信。比如A组件传一个对象给B组件,这就是通信。

二、组件之间通信的常见方式

使用props或vuex可以实现。具体实现可参考:

但他们各有缺陷:

  1. 如果仅仅使用vuex,来实现组件通信,则就有点杀鸡用牛刀了。
  2. 使用props, 在多级包含关系的组件之间传递又太麻烦。

三、如何简单的实现组件多级传递属性和方法

使用v-bind="$attrs"v-on="$listeners"。看下面这个例子

现在有一下三个组件:

grandfather组件:
<template>
  <section>
    <father
      name="name"
      age="18"
      gender="666"
      sdf="asd"
      @isClick="isClick"
      @asd="asd"
    ></father>
  </section>
</template>
<script>
  import father from '~/components/father';
  export default {
    components: {
      father
    },
    methods: {
      asd() {
        console.log('gr', 999);
      },
      isClick() {
        console.log('gr', 666);
      }
    }
  };
</script>

这个组件内部包含了一个father组件,并为father组件传递了四个参数和2个方法。

father组件
<template>
  <section>
    <div class="mt-10">
      <son v-bind="$attrs" v-on="$listeners" />
    </div>
  </section>
</template>

<script>
  import son from '~/components/son';
  export default {
    components: {
      son
    },
    props: {
      name: {
        type: String,
        default: 'default'
      },
      age: {
        type: String,
        default: 'default'
      }
    }
  };
</script>

在father组件中,只递归一了两个入参:name和age。使用了v-bind=“attrs"属性,该属性包含了父作用域中不作为prop被识别(且获取)的特性绑定(class和style除外)。未识别的事件通过‘v−on="attrs" 属性,该属性包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。未识别的事件通过`v-on="attrs"prop()(classstyle)von="listeners”`传入

son组件
<template>
  <section>
    <div>
      {{ $attrs['gender'] }}  在$attrs里面只会有props没有注册的属性
      <br>
      {{ gender }}
    </div>
  </section>
</template>

<script>
  export default {
    props: {
      gender: {
        type: String,
        default: ''
      }
    },
    mounted() {
      console.log('son', this.$attrs);
      console.log('son', this.$listeners);
      this.$listeners.isClick();
      this.$listeners.asd();
    }
  };
</script>

结果

加载爷爷组件grandfather,运行结果如下:

son {sdf: 'asd'}
son {asd: function, isClick: function}

gr 666
gr 999 

页面上显示:
在$attrs里面只会有props没有注册的属性
666 

从结果分析:

1.在儿子组件中,console.log(‘son’, this.$attrs);的结果为什么是 {sdf: ‘asd’}

在爸爸节点中调用儿子组件时,使用了v-bind="attrs"。在儿子节点中的vm.attrs"。在儿子节点中的vm.attrs"vm.attrs只会包含父节点中没有绑定的属性。爷爷那里传过来了name, age, gender, sdf。其中name age在爸爸那里已经定义了,gender在儿子的props里也定义了。所以只有sdf没有定义,结果中就只有sdf属性了

2.在儿子组件中,console.log(‘son’, this.$listeners);的结果为什么是son {asd: function, isClick: function}

通过listeners传递了爷爷中的方法到孙子组件,但是在孙子组件中,不能直接使用该方法,哪怕将同名方法暴露在孙子的props中,在孙子组件里也不能使用爷爷传过来的方法。可以通过vm.listeners传递了爷爷中的方法到孙子组件,但是在孙子组件中,不能直接使用该方法,哪怕将同名方法暴露在孙子的props中,在孙子组件里也不能使用爷爷传过来的方法。可以通过vm.listeners使props使vm.listeners.方法名() 的方式来使用爷爷传递的方法

4.如何理解页面上显示的666

子组件中的gender属性是props中的属性,在爷爷组件中传入了gender的值是666。所以,通过$atter可以直接在爷爷组件传递数据给孙子组件

<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、付费专栏及课程。

余额充值