组件通信的几种方式

父组件向子组件传值

在父组件的子组件标签上,绑定属性,将传递参数作为属性值

<Father>

<Son :money = 'money' />
</Father>

在子组件的props属性中,声明从父组件传来的值

props:['money']

如果想要对传来的参数进行验证,有两种方式

验证参数类型:

props:{
  money : Number  
}

验证参数大小:

props:{
  money : {
        validator(val){
            return val > 3000
        }
    }
}

子组件向父组件传值

为子组件绑定自定义事件,在自定义事件中通过$emit调用标签上绑定的事件

子组件中:

复制代码
<template>
    <div>
        <h3>子组件</h3>
        <button @click="give">发红包</button>
    </div>
</template>


give(){
    // 第二个参数就是子组件向父组件传的值
this.$emit('hide', this.money) }
复制代码

父组件:

<template id='father'>
    <Son @hide='hide'/>
</template> 

hide(val){ // 对接收的数据进行操作 }

兄弟组件之间的传值

使用ref

假设father为父组件,son和girl为子组件,girl要更改son中的值

首先为父组件中的son标签绑定ref

<father>
    <son ref='son'/>
    <girl />
</father>

在son组件中定义更改数据的方法 changeFlag

changeFlag(){
  this.flag = !this.flag  
}

在父组件中定义fn函数,其中this.ref.son就可以获取son组件

fn(){
    this.$refs.son.changeFlag();
}    

父组件再将fn方法当做属性绑定给gir组件

<father>
    <girl :beat='fn'/>
</father>

在girl组件中通props接收,并调用

props:['fn']
methods:{
  beat(){
        this.fn()
    }  
}    

使用事件总线

创建一个vue对象,其中包含$on方法定义事件,$emit方法触发事件

var bus = new Vue()

在需要绑定事件的组件的mounted生命周期函数中绑定事件

mounted(){
// 第一个参数为事件名,自定义。第二个为处理函数 bus.$on(
'hite'. this.changeFlag) }

在需要调用的组件中触发

bus.$emit('hite')

Vuex

数据都存储在store中,通过this.$store.state.属性名调用属性,this.$store.commit(方法名,[参数])调用方法。

只能通过mutation中的方法更改state中的数据

posted @   ashen1999  阅读(623)  评论(0编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
· AI Agent爆火后,MCP协议为什么如此重要!
点击右上角即可分享
微信分享提示