在Vue2.0和Vue3.0中使用v-model
在Vue2.0中如何實現(xiàn)雙向數(shù)據(jù)綁定呢?常用的方式又兩種,一種是v-model,另一種是.sync,為什么會有兩種呢?這是因為一個組件只能用于一個v-model,但是有的組件需要有多個可以雙向響應(yīng)的數(shù)據(jù),所以就出現(xiàn)了.sync。在Vue3.0中為了實現(xiàn)統(tǒng)一,實現(xiàn)了讓一個組件可以擁有多個v-model,同時刪除掉了.sync。如下面的代碼,分別是Vue2.0與Vue3.0使用v-model的區(qū)別。
在Vue2.0中使用v-model
<template>
<a-input v-model="value" placeholder="Basic usage" />
</template>
<script>
export default {
data() {
return {
value: '',
};
},
};
</script>
在Vue3.0中使用v-model
在vue3.0中,v-model后面需要跟一個modelValue,即要雙向綁定的屬性名,Vue3.0就是通過給不同的v-model指定不同的modelValue來實現(xiàn)多個v-model
在使用v-model需要指定modelValue
<template>
<!--在使用v-model需要指定modelValue-->
<custom-input v-model:value="state.inputValue"></custom-input>
</template>
<script>
import { reactive } from "vue";
import CustomInput from "../components/custom-input";
export default {
name: "Home",
components: {
CustomInput
},
setup() {
const state = reactive({
inputValue: ""
});
return {
state
};
}
};
</script>
父子傳
父
<template>
<div>
<div>這里是modelFather</div>
//v-model:ShowName="state.name"
//ShowName 自定義屬性名
//state.name屬性值
<ModelChildren
v-model:ShowName="state.name"
v-model:ShowEmail="state.email"
v-model:ShowPhone="state.phone"
/>
</div>
</template>
<script>
import ModelChildren from './ModelChildren.vue'
import { reactive } from 'vue'
export default {
components: {
ModelChildren
},
setup() {
const state = reactive({
name: '',
email: '',
phone: ''
})
return {
state
}
}
}
</script>
子
<template>
<div>
// $emit('update:ShowName', $event.target.value)
// $emit('update廣播
// ShowName 屬性名 要和父組件的自定義名稱一致
// 改變賦值
<input type="text" placeholder="請輸入姓名" :value="ShowName" @input="$emit('update:ShowName', $event.target.value)"><br>
<input type="text" placeholder="請輸入郵箱" :value="ShowEmail" @input="$emit('update:ShowEmail', $event.target.value)"><br>
<input type="text" placeholder="請輸入電話" :value="ShowPhone" @input="_handleChangeValue" />{{ShowPhone}}
</div>
</template>
<script>
export default {
props: {
ShowName: {
type: String,
default: ""
},
ShowEmail: {
type: String,
default: ""
},
ShowPhone: {
type: String,
default: ""
}
},
setup(props, {emit}) {
function _handleChangeValue($event) {
emit('update:ShowPhone', $event.target.value)
}
return {
_handleChangeValue
}
}
}
</script>