基于vue-cli的组件通讯

根据组件关系划分

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

父子

props/$emit,$on

vue

<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>

this

<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 的自定义事件spa

双向绑定

<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>

子(不用修改)code

<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 不是真正的双向绑定,而是一个语法糖,修改数据仍是在父组件完成的,并不是在子组件component

事件

<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>

ip

<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>
相关文章
相关标签/搜索