简体   繁体   English

从本地子 vue 组件捕获事件

[英]Catch event from local child vue component

My project contains 4 components: Header, Content, Footer, Main.我的项目包含 4 个组件:页眉、内容、页脚、主要。 All of them separeted to .vue files.所有这些都分离为 .vue 文件。 Main.vue file: Main.vue 文件:

<template lang="pug">
.maincomponent
  header
  content
  footer
</template>
<script>
import Header from '@/components/Header'
import Content from '@/components/Content'
import Footer from '@/components/Footer'
export default {
  name: 'Main',
  created: function () {
    console.log('Main component created')
  },
  components: {
    'header': Header,
    'content': Content,
    'footer': Footer
  },
  data () => {
   return {
     mainData: false
   }
  }
}
</script>
<style>
</style>

Header.vue code: Header.vue 代码:

<template lang="pug">
.header {{property}}
    button(@click='buttonClick') Button
</template>
<script>
export default {
  name: 'Header',
  props: {
    property: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    buttonClick: function () {
      this.$emit('headerButtonClick')
    }
  }
}
</script>

<style>
</style>

Updated: With this code I manage to render page properly.更新:使用此代码,我设法正确呈现页面。 Now I want to emit event buttonClick from Header -> catch it in Main -> and set child prop 'property' to data memeber 'mainData'.现在我想从 Header 发出事件 buttonClick -> 在 Main -> 中捕获它,并将子 prop 'property' 设置为 data memeber 'mainData'。 How can I do with this code?我该如何处理这段代码?

You'll have to catch the headerButtonClick event by putting the directive v-on in your template code.您必须通过将指令v-on放在模板代码中来捕获headerButtonClick事件。 Don't have a clue about "pug" language, but it should look something like:对“哈巴狗”语言一无所知,但它应该类似于:

.maincomponent
header (v-on:headerButtonClick="name-of-your-main's-method")
content
footer

After catching that event, you could change the property var in any ways.捕获该事件后,您可以以任何方式更改property var。 According to Vue's documentation ( https://v2.vuejs.org/v2/guide/components.html#Passing-Data-with-Props ), communication between parent and child should be done by:根据 Vue 的文档( https://v2.vuejs.org/v2/guide/components.html#Passing-Data-with-Props ),父子之间的通信应该通过以下方式完成:

  1. Child emits an event to parent子级向父级发出事件
  2. Parent catches the event, does something父母抓住事件,做点什么
  3. Parent sets a prop父母设置一个道具

So, the parent communicates with its child using props and the child using events.因此,父母使用道具与孩子沟通,而孩子使用事件。

Your are emitting headerButtonClick event from your Header Component, Just Catch it on your main component:您正在从您的 Header 组件发出headerButtonClick事件,只需在您的主组件上捕获它:

<template lang="pug">
.maincomponent
  header(@headerbuttonclick='functionToExecute')
  content
  footer
</template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM