I have a main component called App.vue which contains some html div elements and a router-view. Form a component which is assigned to a route, I want to show/hide a div in App.vue (If a button is clicked in child component, show one div in parent, show another div for another button,.etc). I tried passing a prop to router-view and update prop prom child, but it shows error. How can I do this?
0
votes
1 Answers
0
votes
You can listen to an event in router-view
tag and act accordingly:
const child = {
template: `<div style="margin-bottom:100px">
<button @click="$emit('clicked')">Toggle div</button>
</div>`
}
const router = new VueRouter({
routes: [ { path: '/child', component: child } ]
})
new Vue({
router,
el: '#app',
data: { displayMe: 'block' },
methods: {
toggleMe: function() {
this.displayMe = (this.displayMe === 'block') ? 'none' : 'block';
}
}
})
#hideme {
width: 100px;
height: 100px;
background: orange
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<div>
<div id="hideme" :style="{display: displayMe}"></div>
</div>
<router-link to="/child">Visit child</router-link>
<router-view @clicked="toggleMe()"></router-view>
</div>
For multiple divs
you can pass some data with events, and receive it in $event
argument of your handler function (example: toggleMe($event)
), and resolve style properties individually. You can track each div
using ref attribute for example, and save status inside data
object with structure like { '1': 'block', ...}
and retrieve styles using a method.