Vue组件传参的五种方式

本文转自:https://blog.youkuaiyun.com/qq_44375977/article/details/104884834

方法一 props传参

父组件

<template>
    <div class="wrap">
        <div>我是Father组件</div>
        <Son
          str="我是字符串"
          :num=5
          :obj="{cont:'我是一个对象'}"
          :func="()=>{this.hello()}"
          :arr="arr"></Son>
    </div>
</template>
<script>
    import Son from './Son'
    export default {
        name: "Father",
        components:{  Son  },
        data(){
            return{
                arr:[1,2,3]
            }
        },
        methods:{
            hello(){
                console.log("hello world!")
            }
        },
      
    }
</script>

子组件

<template>
    <div>我是Son组件</div>
</template>
<script>
    export default {
        name: "Son",
        props:{//props列表
            arr:Array,//定义参数类型
            num:Number,
            str:String,
            str2:{
                type:String,
                default:"我是默认字符串"//定义参数默认值
            },
            func:{
                type:Function,
                required:false//定义参数是否必须值
            },
            obj:{
                type: Object,
                required:false
            }
        },
        created() {
            console.log(this.str);//我是字符串
            console.log(this.str2);//我是默认字符串
            console.log(this.num);//5
            console.log(this.func);//hello(){console.log("hello world!");}
            console.log(this.arr);//[1,2,3]
            console.log(this.obj);//{cont:'我是一个对象'}
            this.func();//hello world!
        }
    }
</script>

方法二 事件传递

父组件

<template>
    <div class="wrap">
        <div>我是Father组件</div>
        <Son @func="speak" ></Son>
    </div>
</template>

<script>
    import Son from './Son'
    export default {
        name: "Father",
        methods:{
           speak(msg){
               console.log(msg);//我是子组件发送的消息!
           }
        },
        components:{
            Son
        }
    }
</script>

子组件

<template>
    <div>
        <div>我是Son组件</div>
    </div>
</template>

<script>
    export default {
        name: "Son",
        mounted() {
            this.$emit('func',"我是子组件发送的消息!");
        }
    }
</script>


方法三 事件监听

父组件

<template>
    <div class="wrap">
        <div>我是Father组件</div>
        <Son ref="son"></Son>
    </div>
</template>

<script>
    import Son from './Son'
    export default {
        name: "Father",
        mounted(){
            this.$refs['son'].$on('func',(msg)=>{
                console.log(msg);
            })
        },
        components:{
            Son
        }
    }
</script>

子组件

<template>
    <div>
        <div>我是Son组件</div>
        <button @click="$emit('func','我是子组件传递的消息1!')">Send1</button>
        <button @click="sendMsg">Send2</button>
    </div>
</template>

<script>
    export default {
        name: "Son",
        methods:{
            sendMsg(){
                this.$emit('func','我是子组件传递的消息!');
            }
        }
    }
</script>

方法四 消息发布与订阅

安装 pubsub-js 插件: npm i pubsub-js -s 可实现全局参数传递

父组件

<template>
    <div class="wrap">
        <div>我是组件A</div>
        <button @click="sendMsg">发送</button>
    </div>
</template>

<script>
    import  pubsub from 'pubsub-js'
    export default {
        name: "A",
        methods:{
            sendMsg(){
                pubsub.publishSync("sendMsg","这是A组件发布的消息!");
            }
        }
    }
</script>


子组件

<template>
    <div>
        <div>我是组件B</div>
    </div>
</template>

<script>
    import pubsub from 'pubsub-js'
    export default {
        name: "B",
        mounted(){
            pubsub.subscribe("sendMsg",(e,msg)=>{
                console.log(e,msg);//sendMsg 这是A组件发布的消息!
            })
        },
    }
</script>

publishSync
同步发送消息
publish
同步发送消息
subscribe
订阅消息
unsubscribe
卸载特定订阅
clearAllSubscriptions
清除所有订阅

方法五 EventBus传参

1.在main.js种挂载全局EventBus

Vue.prototype.$EventBus = new Vue()

2.A组件

<template>
    <div class="wrap">
        <div>我是组件A</div>
        <button @click="sendMsg">发送</button>
    </div>
</template>

<script>
    export default {
        name: "A",
        methods:{
            sendMsg(){
               this.$EventBus.$emit('sendMsg',"这是组件A发送的消息!")
            }
        }
    }
</script>

3.B组件

<template>
    <div>
        <div>我是组件B</div>
    </div>
</template>

<script>
    export default {
        name: "B",
        mounted(){
            this.$EventBus.$on('sendMsg',(msg)=>{
                console.log(msg);//这是组件A发送的消息!
            })
        },
    }
</script>

### Vue 组件传参方法及其实现 在 Vue 中,组件之间的参数传递是一个常见的需求。以下是几种主要的组件传参方式及其具体实现: #### 1. **父组件向子组件传参** 通过 `props` 实现父子组件间的单向数据流。父组件可以通过定义属性的方式将数据传递给子组件。 ```html <!-- 父组件 --> <template> <ChildComponent :message="parentMessage"></ChildComponent> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentMessage: 'Hello, child!' }; } }; </script> ``` 子组件接收该参数并声明为 `props` 属性之一[^1]。 ```javascript // 子组件 export default { props: ['message'], mounted() { console.log(this.message); // 输出:Hello, child! } } ``` #### 2. **子组件向父组件传参** 利用 `$emit` 方法触发自定义事件来通知父组件某些状态的变化。 ```html <!-- 子组件 --> <template> <button @click="sendDataToParent">Send Data to Parent</button> </template> <script> export default { methods: { sendDataToParent() { this.$emit('child-event', 'This is a message from the child'); } } }; </script> ``` 父组件监听此事件,并处理接收到的数据[^1]。 ```html <!-- 父组件 --> <template> <ChildComponent @child-event="handleChildEvent"></ChildComponent> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { handleChildEvent(data) { console.log(data); // 接收来自子组件的消息 } } }; </script> ``` #### 3. **兄弟组件之间通信** 可以借助共同的父级组件作为中介来进行消息传递,或者使用 Vuex 或者 Pinia 这样的全局状态管理工具。另一种简单的方法是创建一个事件总线(Event Bus)[^2]。 ##### 使用 Event Bus 的例子: 首先初始化 event bus: ```javascript // main.js or utils/eventBus.js import Vue from 'vue'; export const EventBus = new Vue(); ``` 然后在一个组件中发送事件,在另一个组件中监听它: ```javascript // 发送方组件 this.EventBus.$emit('event-name', payload); ``` ```javascript // 接收方组件 created() { this.EventBus.$on('event-name', (payload) => { // 处理逻辑... }); }, beforeDestroy() { this.EventBus.$off('event-name'); // 清除事件以防内存泄漏 } ``` #### 4. **跨层级组件通信** 对于更复杂的场景,推荐采用 Vuex/Pinia 来集中存储应用的状态信息,从而允许任何地方都能方便地读取或修改这些共享的信息[^2]。 --- ### 总结 以上介绍了四种常见 Vue 组件传参的技术手段,分别是基于 Props 和 Events 的基本模式以及高级解决方案如 Event Bus 及 State Management Libraries(Vuex / Pinia)。每种技术都有其适用范围和优缺点,请根据实际项目情况选择合适的方式来构建高效的应用程序结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值