S
S
ssvwvhas2018-06-11 19:39:50
Vue.js
ssvwvhas, 2018-06-11 19:39:50

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 components
buttonShow = false;
this.$parent.buttonShow = true;this.$parent.buttonShow = false;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Askhat Bikmetov, 2018-06-11
@ssvwvhas

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>

The first argument of the handler is the event object, and the method $emitaccepts arbitrary data as the event payload (the second argument of the handler).
2. Use the store
// store.js
export default {
  state: {
    buttonShow: false
  },
  mutations: {
    buttonToggle: state => (state.buttonShow = !state.buttonShow)
  }
}

The mechanics of working in a component are almost the same, with the exception that the click handler in the child component must commit the mutation:
clickHandler () {
  this.$store.commit('buttonToggle')
}

And the parent component, in turn, gets rid of the subscription to @toggle-buttonand 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 question

Ask a Question

731 491 924 answers to any question