组件通信的几种方式

父组件向子组件传值

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

<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.state.commit(方法名,[参数])调用方法。

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

猜你喜欢

转载自www.cnblogs.com/ashen1999/p/12795246.html