This question is more about how to architect the components in such a way to share data between them. There are many ways to do this, each with their own pros and cons depending on the situation. I suggest you search stackoverflow/google for ways to do this because it has been discussed in depth.
Raise the owner of the userCount
data to the parent
Make the parent component the owner of the userCount
data, and pass this down to the child components via props. If the child components want to modify that data, they must $emit
an event with the new value which the parent responds to so it can update the value.
const Daily = {
props: ['userCount'],
template: '<p>Daily: {{ userCount }} <button @click="increment">+ 1</button></p>',
methods: {
increment() {
this.$emit('user-count', this.userCount + 1);
}
}
};
const Weekly = {
props: ['userCount'],
template: '<p>Weekly: {{ userCount }} <button @click="increment">+ 5</button></p>',
methods: {
increment() {
this.$emit('user-count', this.userCount + 5);
}
}
};
new Vue({
el: '#app',
router: new VueRouter({
routes: [
{ path: '/daily', component: Daily },
{ path: '/weekly', component: Weekly }
]
}),
data: {
userCount: 0,
},
})
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>
<div id="app">
<router-link to="/daily">Daily</router-link>
<router-link to="/weekly">Weekly</router-link>
<router-view :user-count="userCount" @user-count="userCount = $event"></router-view>
</div>
Vuex or some other external state management
There's already lots of Vuex examples so I won't replicate that here, but you can come up with any kind of state management system you want.
Vuex may be overkill for your example. You can just pass around a shared reactive object instead.
const Daily = {
props: ['shared'],
template: '<p>Daily: {{ shared.userCount }} <button @click="increment">+ 1</button></p>',
methods: {
increment() {
this.shared.userCount += 1;
}
}
};
const Weekly = {
props: ['shared'],
template: '<p>Weekly: {{ shared.userCount }} <button @click="increment">+ 5</button></p>',
methods: {
increment() {
this.shared.userCount += 5;
}
}
};
new Vue({
el: '#app',
router: new VueRouter({
routes: [
{ path: '/daily', component: Daily },
{ path: '/weekly', component: Weekly }
]
}),
data: {
shared: {
userCount: 0,
}
},
})
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>
<div id="app">
<router-link to="/daily">Daily</router-link>
<router-link to="/weekly">Weekly</router-link>
<router-view :shared="shared"></router-view>
</div>