3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【知らなかった】Vue.js Nuxt.js 親からpropsで渡した値を子から更新する方法

Last updated at Posted at 2021-07-05

#NGパターン

###親

<template>
  <div>
    <Children :message="message" />
  </div>
</template>

<script>
import Children from '~/components/Children.vue'

export default {
  components: {
    Children,
  },
  data() {
    return {
      message: 'メッセージ',
    }
  },
}
</script>

###子

Children.vue
<template>
  <div>
    <input type="text" v-model="message" />
  </div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
    },
  },
}
</script>

上記の事をしたいが、どうしても以下エラーが出る...

Avoid mutating a prop directly since the value will 
be overwritten whenever the parent component re-renders. 
Instead, use a data or computed property based on 
the prop's value. Prop being mutated: "message"
...

propsの値を直接変更しないでね、って言ってます

OKパターン

###親

<template>
  <div>
    <Children :message.sync="message" />
  </div>
</template>

<script>
import Children from '~/components/Children.vue'

export default {
  components: {
    Children,
  },
  data() {
    return {
      message: 'メッセージ',
    }
  },
}
</script>

  • 親で.syncを使う

###子

Children.vue
<template>
  <div>
    <input type="text" :value="message" @input="inputMessage" />
  </div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
    },
  },
  methods: {
    inputMessage(e) {
      this.$emit('update:message', e.target.value)
    },
  },
}
</script>
  • 子では、v-modelは使用せず、inputイベントでupdate:props名

これで親と子のmessageが同期されて更新できます

知らなかったけど、めっちゃ便利

3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?