Answer the question
In order to leave comments, you need to log in
How to change the variable in the parent component if there is no variable in the child?
Good evening. I create a single page application
In the parent component, let's say there is a variable that shows a button.
This button is only needed on a few pages. If set in a child element: then the button will always remain active, is it possible to make the variable equal to false always, and only insert true on certain components. Or you will have to write on all other componentsbuttonShow = false;
this.$parent.buttonShow = true;
this.$parent.buttonShow = false;
Answer the question
In order to leave comments, you need to log in
You should not directly modify the state of the parent component, this is contrary to the unidirectional data flow architecture. Instead, you must use one of the following options:
1. Send an event
// parent.vue
<template>
<parent>
<child @toggle-button="toggleButtonHandler"/>
</parend>
</template>
<script>
export default {
data: {
return {
buttonShow: false
}
},
methods: {
toggleButtonHandler () {
this.buttonShow = !this.buttonShow
}
}
}
</script>
// child.vue
<template>
<button @click="clickHandler">Hide Button</button>
</template>
<script>
export default {
methods: {
clickHandler () {
this.$emit('toggle-button')
}
}
}
</script>
$emit
accepts arbitrary data as the event payload (the second argument of the handler). // store.js
export default {
state: {
buttonShow: false
},
mutations: {
buttonToggle: state => (state.buttonShow = !state.buttonShow)
}
}
clickHandler () {
this.$store.commit('buttonToggle')
}
@toggle-button
and no longer keeps its own state, but subscribes to the store:computed: {
buttonShow () {
return this.$store.state.buttonShow
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question