0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue.jsでProvide Injectする際の値変更の時の備忘録

Posted at

経緯

Vue.jsで子コンポーネント(injectしている側)側で値を変更しようとしたらコードレビューの際に指摘された。
どうやらベストプラクティスは親コンポーネント(Provide)側で値を変更する関数を書き、子コンポーネントでその関数を呼び出すことらしい。
参照:
https://ja.vuejs.org/guide/components/provide-inject

Provide(親)コンポーネント内部
<script setup>
import { provide, ref } from 'vue'

const location = ref('North Pole')

function updateLocation() {
  location.value = 'South Pole'
}

provide('location', {
  location,
  updateLocation
})
</script>
inject(子)コンポーネント内部
<script setup>
import { inject } from 'vue'

const { location, updateLocation } = inject('location')
</script>

<template>
  <button @click="updateLocation">{{ location }}</button>
</template>

結論

ドキュメントをしっかり読もうと思いました。。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?