vue中的组件间通信

2020-07-04  本文已影响0人  东方三篇

父子组件相互通信

```bash
# 父组件
<template>
  <div>
    # 使用引入的子组件, 没有 :是静态传值, :是 v-bind的简写, 指的是动态传值
    # .sync 修饰符,可以显性的让 子组件 更新 父组件 age 的值,实现 ‘双向绑定’
    # <son :age.sync="age" /> 会被vue默认拓展成 <son :age="age" @update:age=val=>age=val /> 在子组件里也需要 emit 触发更新
    # v-on传方法给子组件 v-on: 可以用 @简化
    <Son name="York" :birth="birth" :sex="sex" :age.sync="age" /* v-on:counter="notice" */ @counter="notice"> </Son>
  </div>
</template>
<script>
  import Son from './son'
  export defaulte {
    name: 'Father',
    data () {
      birth: '1988-8-1',
      sex: 'male',
      age: 18
    },
    components: {Son}
    methods: {
      notice (val) {
        console.log('子组件触发父组件的方法,病传值 val 回来!', val)
        this.birth = this.format(val)
      },
      format () { ... }
    }
  }
</script>
```

```bash
# 子组件
<template>
  <div>{{name}}:{{birth}}:{{sex}}</div>
  <button @click="passBirth(val)">更新生日</button>
  <button @click="updateAge(val)">更新年龄</button>
</template>
<script>
  export defaulte {
    name: 'Son',
    # 用props接收父组件传入的值,并可以做校验
    # props: ['name', 'birth', 'sex'] 不做校验的方法
    props: {
      name: String,
      birth: [String, Number],
      sex: {
        type: String,
        required: true,
        default: 'male'
      },
      age: {
        validator: value => {
          return value > 10 // 自定义校验
        }
      }
    }
    data () {},
    methods: {
      passBirth (val) {
        this.$emit('counter', val) // count是父组件传入的方法名, 在子组件内调用
      },
      updateAge (newValue) {
        this.$eimt('upadte:age', newValue) // 触发更新 父组件 通过 .sync 修饰符 传入的 age 值
      }
    }
  }
<script>
```

非父子组件间通信

可以用一个空的 Vue 实例,作用中央事件总线, 不过比较复杂的场景, 个人更倾向于使用 vuex。

关于vuex请查阅: https://www.jianshu.com/writer#/notebooks/45129165/notes/72862417

上一篇 下一篇

猜你喜欢

热点阅读