(六)组件通信

44 阅读1分钟

子传父

子传父操作:

首先,需要在子组件中定义好在某些情况下触发的事件名称;

其次,在父组件中以v-on的方式传入要监听的事件名称,并且绑定到对应的方法中;

最后,在子组件中发生某个事情的时候,根据事件名称触发对应的事件。

image.png

父组件改变counter

image.png

实现一个综合案例 父组件计数将值给子组件传过去。子组件价格点击父组件处理。

父组件
<template>
  <h1>{{title}}</h1>
  <h2>当前计数: {{counter}}</h2>
  <button @click="increment">+1</button>
  <button @click="decrement">-1</button>

  <h2>当前价格:{{ price }}</h2>
  <product-item :counter="counter" @changeCount="changeclick"></product-item>


</template>

<script>
import ProductItem from './ProductItem.vue'

export default {
  components: {
    ProductItem
  },
  data() {
    return {
      title: "我是父组件",
      counter: 0,
      price: 99
    }
  },
  methods: {
    increment() {
      this.counter++
    },
    decrement() {
      this.counter--
    },
    changeclick(count) {
      this.price -= count
    }
  }
}
</script>

<style>
  h2 {
    color: red;
  }
</style>

子组件
<template>
  <div class="product">
    <h1>我是子组件</h1>
    <div>父组件内容传到子组件: {{counter}}</div>

    <p>修改父组件的价格</p>
    <button @click="discount(2)">减2元</button>
    <button @click="discount(5)">减5元</button>
    
  </div>
</template>

<script>

export default {
  props:{
    counter: Number
  },
  methods:{
    discount(count) {
      this.$emit("changeCount", count)
    }
  }
}

</script>

<style>
</style>