※ ぱっと見でわかるように説明と文法の省略をしています。
前提知識
<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-bindとv-on
// Child
<input
:value="title"
@input="$emit('input', $event.target.value)"
>
props: {
title: {
type: String,
},
},
computed 使ったやり方
- 親コンポーネントは
v-model - 子コンポーネントは
computedのgetとset-
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);
},
},
参考