3👍
✅
If your two apps become components with a common parent, the proper behavior is:
- The parent owns a
selectedUser
data item - The
user
component emits an event when a user is clicked - The parent receives the emitted event and updates
selectedUser
from it - The
building
component receivesselectedUser
as a prop - The
building
componentwatch
esselectedUser
and updates itsbuildings
data item accordingly.
The main app looks like this:
<div id="app">
<user @selected-user="setSelected"></user>
<building :selected-user="selectedUser"></building>
</div>
The snippet below demonstrates the behavior I’ve described.
new Vue({
el: '#app',
data: {
selectedUser: null
},
components: {
user: {
template: '#user-template',
data: () => ({
users: [{
firstName: 'First',
lastName: 'One',
address: '1 1st St',
phone: '111-1111',
email: 'one@example.com',
password: '111112',
isActive: false,
}]
}),
methods: {
toggleClicked: function(user) {
this.$emit('selected-user', user);
},
}
},
building: {
template: '#building-template',
props: ['selectedUser'],
data: () => ({
buildings: [{
buildingName: 'None',
address: 'nowhere',
buildingYear: '1969 - nice'
}]
}),
watch: {
selectedUser(newValue) {
this.buildings = [{
buildingName: `${newValue.firstName}'s building`,
address: newValue.address,
buildingYear: 'still 1969 - nice'
}];
}
}
}
},
methods: {
setSelected(user) {
this.selectedUser = user;
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template id="user-template">
<ul class="collection">
<a href="#!" class=" collection-item avatar" v-for="user in users" v-bind:class="" v-on:click="toggleClicked(user)">
<!-- v-bind:class="active: isActive" -->
<i class="material-icons circle">folder</i>
<span class="name"><strong>{{ user.firstName + " " + user.lastName }}</strong></span>
<p> {{ user.phone }} </p>
<p> {{ user.email }} </p>
<a href="#!" class="secondary-content"></a>
</a>
</ul>
</template>
<template id="building-template">
<div class="collection">
<a href="#!" class=" collection-item avatar" v-for="Building in buildings" v-bind:class="" v-on:click="toggleClicked(Building)">
<!-- v-bind:class="active: isActive" -->
<i class="material-icons circle">folder</i>
<span class="name"><strong>{{ Building.buildingName }}</strong></span>
<p> {{ Building.address }} </p>
<p>Byggeår: {{ Building.buildingYear }} </p>
<a href="#!" class="secondary-content"></a>
</a>
</div>
</template>
<div id="app">
<user @selected-user="setSelected"></user>
<building :selected-user="selectedUser"></building>
</div>
Source:stackexchange.com