How to update state of child component in VueJS

Calendar Clock iconCalendar Clock icon

vuejs

Table of contents

When you want to update the state of child's component through its parent in VusJS, like open or close a dialog as child component, you can use ref.

No additional settings are needed for child component.
Add ref="hoge" attribute to child component, when embed in parent component's template.
Parent can access child's data fields through this.$refs['hoge'].

# Sample code

# Child component

<template>
<div v-show="visible">
  <h1>I'm child.</h1>
  <button @click="visible = false">Close</button>
</div>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
    }
  }
}
</script>

# Parent component

<template>
<div>
  <button @click="onClick">Open</button>
  <child ref="child" />
</div>
</template>

<script>
import child from './child';

export default {
  components: { child },
  methods: {
    onClick() {
      this.$refs['child'].visible = true;
    }
  }
}
</script>

Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!

Offer jobs or contact me!

Comments