Search code examples
vue.jseventsevent-handlingvuejs3

Vue.js template listen to message


I have this template "template-main":

...
<template>
          ...
          <slot></slot>
          ...
</template>
...

Than I have my simple page that use this template

<template>
  <template-main>
    ...code of my page...
  </template-principal>
</template>

I Want to know how to send one message from my page to my template in the way that i can change a value of a variable of template-main.

I try this: on my simple page I lauch my event with:

 this.$emit('message-to-template', 'hello'); 

on my template i listen to this message with:

<slot @message-to-template="handleMensagemRecebida"></slot>

but this dont work! how to solf this?


Solution

  • If I understand correctly, you want to emit a event from template-main to your singple page.

    On template-main component you have to emit a event by @click

    <template>
    ...
         <slot>
            <button @click="$emit('message-to-template', 'hello')"></button>
        </slot>
          <p>{{ message }}</p>
    ...
    </template>
    
    
    
    <script>
    export default {
         emits: ['message-to-template'],
         props:['message']
    
    }
    </script>
    

    Anh handle it like on your single page

    <template>
      <template-main message="hi" @message-to-template="handleMensagemRecebida">
        ...code of my page...
      </template-main>
    </template>
    
    

    This code is for Option API