Alexeymsa
Alexeymsa

Reputation: 45

how to pass data between different template

I'm trying to make a chat and I do not know how to click an item in one template get the data and transfer it to another. from #template1 to #template2

const app = new Vue({
    el: '#content',
    data:{
      users: [],
      messages: []
    }
});

template1

<template lang="html">
<li v-on:click="getMessages()">
  <div class="content-container">
    <span class="name">{{ user.first_name}} {{user.last_name}}</span>
    <span class="txt"></span>
  </div>
</li>
</template>


<script>
export default {
props: ['user'],
data: function() {
    return {
      messages: []
    };
  },


methods: {
getMessages(id) {
    this.$http.get('/admin/chat/messages').then(function(res){
        this.messages = res.data;
    }
    },
}
}
</script>

template2

<template lang="html">
<ul class="chat">
  <chat-message v-for="message in messages" :key="+message" :message="message"></chat-message>
</ul>
</template>


<script>
export default {
  props: ['messages']
}
</script>

how to pass data between this template

The structure is:

el: #content
<div id="content">

    <div class="list-text" id="chatbox">
      <user-list :users="users">#template1</user-list>
    </div>

    <div class="list-chat">
      <chat-log :messages="messages">#template2</chat-log>
      <chat-composer v-on:messagesent="addMessage"></chat-composer>
    </div>

</div>

When I click on the user in the user-list i'm trying to load messages from this user and I do not know how to pass them in chat-log

Upvotes: 1

Views: 632

Answers (1)

Duy Anh
Duy Anh

Reputation: 770

There are a few ways to achieve the communication between the components

  1. Emit and listen to event (if the component are siblings, you will have to go through the parent) - this solution is fine if you have very little components that need to communicate with each other
  2. Use event bus -> every event will go through this bus (good tutorial on how to create an event bus)
  3. Use vuex - state management (just like event bus, but better, if you have a lot of component communication)

Upvotes: 1

Related Questions