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?

More than 3 years have passed since last update.

v-modelとpropsとstore(vuex)

Last updated at Posted at 2021-10-15

※ ぱっと見でわかるように説明と文法の省略をしています。

前提知識

<input v-model="title" />

は ⇩ の 糖衣構文 (シンタックスシュガー = 簡単な書き方)

<input
  :value="title"
  @input="title = $event.target.value"
/>

親子間の v-model パターン

親コンポーネント

// Parent
<child-component
   v-model="title"
  />

data() {
  return {
    title: "",
  };
},

ノーマル なやり方

  • 親コンポーネントは v-model
  • 子コンポーネントは v-bindv-on
// Child

<input
    :value="title"
    @input="$emit('input', $event.target.value)"
  >

props: {
    title: {
      type: String,
    },
  },

computed 使ったやり方

  • 親コンポーネントは v-model
  • 子コンポーネントは computedgetset
    • get は値を取得
    • set は値の変更を検知してイベント発火
// Child
<input
    v-model="inputedValue"
	/>

props: {
    title: {
      type: String,
    },
  },
computed: {
    inputedValue: {
      get() {
        return this.title;
      },
      set(newValue) {
        this.$emit("input", newValue);
      },
    },
  },

store(vuex)絡み

store.js

state: {
  title: '',
},
mutations: {
  updateTitle(state, title) {
    state.title = title;
  },
},

親コンポーネント

<child-component
    :title="title"    
    @update-title="updateTitle($event)"
  />

computed: {
    title() {
      return this.$store.state.title;
    },
  },
methods: {
    updateTitle(value) {
       this.$store.commit('updateTitle', value);
    },
  },

参考

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?