VUE中$emit的使用方法

定义

$emit的主要作用是子组件触发父组件的事件。

语法:

$emit(event, args)

$emit主要用于子组件中某些的事件需要父组件做出响应时的场景。

示例

  • 子组件定义
<template>
  <div>
    <input v-model="name" @input="handleChange">
  </div>
</template>

<script>
export default {
  name: "Child",
  data(){
    return {
      name:'Jack'
    }
  },
  methods: {
    handleChange(){
      this.$emit('change', this.name)
    }
  }
}
</script>
  • 父组件定义
<template>
  <div>
    <h1> hello {{name}}</h1>
    <child @change="parentEvent"></child>
  </div>
</template>

<script>
import Child from "@/components/Child";
export default {
  name: "Parent",
  components: {Child},
  data(){
    return {
      name:'Tom'
    }
  },
  methods: {
    parentEvent(name) {
      this.name = name;
    }
  }
}
</script>
  • 结果

进入页面效果

任意输入后效果

# VUE  $emit  组件 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×