基于vuecli的组件通信

23次阅读

共计 1777 个字符,预计需要花费 5 分钟才能阅读完成。

根据组件关系划分

  1. 父子
  2. 跨级
  3. 无关系

父子

props/$emit,$on

<template>
  <div>
    <test3-a :value="value"
             @input="handleChange"></test3-a>
  </div>
</template>
<script>
import test3A from '../components/test3-a.vue'

export default {components: { test3A},
  data () {
    return {value: 1}
  },
  methods: {handleChange (val) {this.value = parseInt(val)
    }
  }
}
</script>

<template>
  <div>
    <button @click="increase(-1)"> 减 1 </button>
    <span> {{currentValue}} </span>
    <button @click="increase(1)"> 加 1 </button>
  </div>
</template>
<script>
export default {
  props: {
    value: {type: Number}
  },
  data () {
    return {currentValue: this.value}
  },
  methods: {increase (val) {
      this.currentValue = this.value + val
      this.$emit('input', this.currentValue)
    }
  }
}
</script>

props/$emit,$on(v-model 写法)

v-model 是一个语法糖,可以拆解为 props: value 和 events: input。就是说组件必须提供一个名为 value 的 prop,以及名为 input 的自定义事件

<template>
  <div>
    <test3-a v-model="value"></test3-a>
  </div>
</template>
<script>
import test3A from '../components/test3-a.vue'

export default {components: { test3A},
  data () {
    return {value: 1}
  }
}
</script>

子 (不用修改)

<template>
  <div>
    <button @click="increase(-1)"> 减 1 </button>
    <span> {{currentValue}} </span>
    <button @click="increase(1)"> 加 1 </button>
  </div>
</template>
<script>
export default {
  props: {
    value: {type: Number}
  },
  data () {
    return {currentValue: this.value}
  },
  methods: {increase (val) {
      this.currentValue = this.value + val
      this.$emit('input', this.currentValue)
    }
  }
}
</script>

props/$emit,$on(.sync 写法)

.sync 不是真正的双向绑定,而是一个语法糖,修改数据还是在父组件完成的,并非在子组件

<template>
  <div>
    <test3-a :value.sync="value"></test3-a>
  </div>
</template>
<script>
import test3A from '../components/test3-a.vue'

export default {components: { test3A},
  data () {
    return {value: 1}
  }
}
</script>

<template>
  <div>
    <button @click="increase(-1)"> 减 1 </button>
    <span> {{value}} </span>
    <button @click="increase(1)"> 加 1 </button>
  </div>
</template>
<script>
export default {
  props: {
    value: {type: Number}
  },
  methods: {increase (val) {this.$emit('update:value', this.value + val)
    }
  }
}
</script>

正文完
 0