vue父子组件传参之ref

本文详细介绍了在Vue中如何实现父子组件之间的传值,通过使用$ref和ref,演示了如何在子组件中更新数据并通过事件向外暴露,最终在父组件中获取子组件的数据进行汇总。

在vue中,传参的常用的就父子组件传参,兄弟组件传参。今天我们说的是父子组件传参中的一种方式$ref和ref

首先我们创建一个子组件 并给他添加一个number的值和绑定一个点击事件@click='add()',每次点击加1

  Vue.component('counter', {
            template: `<div @click='add'>{{number}}</div>`,
            data() {
                return {
                    number: 0
                }
            },
       methods: {
        add() {
          this.number++
        }
       },
        })

 

  并在我们父组件中调用它

<div id='app'>
   <div>
     <counter></counter>
     <counter></counter>
     <div>{{total}}</div>
   </div>
</div>


并且在子组件中使用change方法暴露出去

this.$emit('change')

 当子组件发生改变的时候像外暴露,我们可以打印出来看看

console.log(this.$emit('change')) 

很显然我们得change方法是起作用了的     

<counter ref="one" @change='hand'></counter>
<counter ref="two" @change='hand'></counter>

我们再通过ref 传入两个参数,并且添加change事件

在父组件中写入
  var app = new Vue({
    el: '#app',
    data:{
      total:0
    },
    methods:{
      hand(){
        this.total = this.$refs.one.number+ this.$refs.two.number
      }
    }
  })

这样我们就完成了父组件的传值

 

完整代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='vue.js'></script>
</head>
<body>
    <div id='app'>
        <counter ref='one' @change='hand'></counter>
        <counter ref='two' @change='hand'></counter>
        <div>{{total}}</div>
    </div>

    <script>
        Vue.component('counter',{
            template:`<div @click='add'>{{number}}</div>`,
            data() {
                return {
                    number:0
                }
            },
            methods: {
                add() {
                    this.number++
                    this.$emit('change')
                    console.log(this.$emit('change'))
                }
            },
        })
        var app = new Vue({
            el:'#app',
            data:{
                total:0
            },
            methods:{
                hand () {
                    this.total = this.$refs.one.number+this.$refs.two.number
                }
            }

        })
    </script>
</body>
</html>

 

转载于:https://www.cnblogs.com/yang656/p/10184335.html

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

余额充值