Vue3: v-model

一、组件 v-model

       在Vue2中,v-model 多用于原生的表单元素,而在Vue3中,v-model可以用在组件上。当v-model用在组件上时,v-model 会被展开为如下形式:

<CustomInput
  :modelValue="searchText"
  @update:modelValue="newValue => searchText = newValue"
/>

        在子组件上使用 v-model 时,父组件会默认向子组件传递一个props 以及派发一个 修改事件。这个 props 名字是固定的: modelValue

如何实现父子组件之间的双向绑定?其实就两步:

        1. 子组件接收父组件 v-model 时传来的 modelValue 和 派发的 'update:modelValue'

        2. 当子组件修改 modelValue 的值时,触发父组件派发的修改的事件。

以下是一个完整栗子:

父组件:

<template>
  <button @click="()=>isShow = !isShow">开关Demo3</button>
  <div>isShow: {{ isShow }}</div>
  <Demo3 v-model="isShow"></Demo3>
</template>
<script setup lang="ts">
// 安装了 unplugin-auto-import 可以自动引入ref,reactive ....
import Demo3 from './components/Demo3.vue';

const isShow = ref<boolean>(true)

</script>

子组件:

<script setup lang="ts">
defineProps(['modelValue'])
defineEmits(['update:modelValue'])
const close = () => {
    emit('update:modelValue', false)
}

</script>

<template>
  <div class="dialog" v-if="modelValue">
    {{ modelValue }}
    <button class="close" @click="close">关闭</button>
    <h3>我是Demo3子组件</h3>
  </div>
</template>
<style scoped>
.dialog{
    width: 500px;
    padding: 10px;
    border: 5px solid #ccc;
    position: relative;
    overflow: auto;
}
.close{
    position: absolute;
    right: 10px;
}
</style>

 上面的例子中,子组件为一个弹窗,父组件通过v-model绑定isShow属性,子组件接收默认的Props和Emits,并绑定自身,来控制子组件的弹出和隐藏。

二、v-model 的参数 和 多个 v-model

        默认情况下,组件中使用v-model,默认传递的props是 modelValue,如果不想用 modelValue这个属性名,我们可以给 v-model 指定一个参数来改变这个名字。

语法:v-model:参数名="响应式变量"

这样我们可以在一个组件上使用多个 v-model。

在之前的栗子上更改一下:

// 父组件
<template>
  <button @click="()=>isShow = !isShow">开关Demo3</button>
  <div>isShow: {{ isShow }}</div>
  <div>text: {{ text }}</div>
  <Demo3 v-model="isShow" v-model:textVal="text"></Demo3>
</template>

<script setup lang="ts">
import Demo3 from './components/Demo3.vue';

const isShow = ref<boolean>(true)
const text = ref<string>('基尼太没')

</script>
<script setup lang="ts">
defineProps<{
    modelValue: boolean,
    textVal: string
}>()
defineEmits(['update:modelValue', 'update:textVal'])
const close = () => {
    emit('update:modelValue', false)
}
const change = (e:Event) => {
    const target = e.target as HTMLInputElement
    emit('update:textVal', target.value)
}
</script>

<template>
  <div class="dialog" v-if="modelValue">
    {{ modelValue }}
    <button class="close" @click="close">关闭</button>
    <h3>我是Demo3子组件</h3>
    内容:<input type="text" :value="textVal" @input="change">
  </div>
</template>

三、v-model 自定义修饰符

        Vue 有一些内置的修饰符,比如 .trim、.lazy 和 .number。在某些场景下,我们可以使用自定义修饰符。

        我们在组件上的 v-model中使用修饰符时,父组件会向子组件传递 一个props:modelModifiers,这个属性名也是固定的,这个属性是一个对象,我们可以在这个对象中访问到这个修饰符。这个props默认是一个空对象。比如下面的栗子中,modelModifiers的值是 {capitalize: true},我们可以通过判断这个修饰符对应的属性值,对modelValue进行一些操作。

<MyComponent v-model.capitalize="myText" />
<script setup>
const props = defineProps({
  modelValue: String,
  modelModifiers: { default: () => ({}) }
})

defineEmits(['update:modelValue'])

console.log(props.modelModifiers) // { capitalize: true }
</script>

<template>
  <input
    type="text"
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
  />
</template>

如果我们想在修改了名字的v-model中使用修饰符怎么办呢,其实就把props中的 'modelModifiers' 改为 '参数名Modifiers' 就可以了。

以下是一个完整案例:

<!-- 父组件  -->
<template>
  <button @click="()=>isShow = !isShow">开关Demo3</button>
  <div>isShow: {{ isShow }}</div>
  <div>text: {{ text }}</div>
  <Demo3 v-model="isShow" v-model:textVal.kun="text"></Demo3>
</template>

<script setup lang="ts">
import Demo3 from './components/Demo3.vue';

const isShow = ref<boolean>(true)
const text = ref<string>('基尼太没')

</script>
<script setup lang="ts">
const props = defineProps<{
    modelValue: boolean,
    textVal: string,
    // textValModifiers 默认值为一个空对象,如果修饰符被使用,则该属性为 true
    textValModifiers?:{
        kun: boolean
    }
}>()
const emit = defineEmits(['update:modelValue', 'update:textVal'])
const close = () => {
    emit('update:modelValue', false)
}
const change = (e:Event) => {
    const target = e.target as HTMLInputElement
    emit('update:textVal', props?.textValModifiers?.kun ? target.value+'唱,跳,rap,篮球' : target.value)
}
</script>

<template>
  <div class="dialog" v-if="modelValue">
    {{ modelValue }}
    <button class="close" @click="close">关闭</button>
    <h3>我是Demo3子组件</h3>
    内容:<input type="text" :value="textVal" @input="change">
  </div>
</template>

<style scoped>
.dialog{
    width: 500px;
    padding: 10px;
    border: 5px solid #ccc;
    position: relative;
    overflow: auto;
}
.close{
    position: absolute;
    right: 10px;
}
</style>

四、defineModel() 宏

        从 Vue 3.4 开始,推荐的实现方式是使用 defineModel() 宏:

语法:const model = defineModel()

defineModel() 会返回一个自定义Ref对象。在修改父组件时,就不需要触发父组件派发的emits了,可以直接修改这个自定义Ref对象的值,同时父组件的数据也会被修改,我们来改造一下上面的栗子:

父组件:

<template>
  <div>
      <button @click="()=>isShow = !isShow">开关Demo3</button>
      <div>isShow: {{ isShow }}</div>
      <Demo3 v-model="isShow"></Demo3>
  </div>
</template>

<script setup lang="ts">
// 安装了 unplugin-auto-import 可以自动引入ref,reactive ....
import Demo3 from './components/Demo3.vue';

const isShow = ref<boolean>(true)
</script>

子组件:

<script setup lang="ts">
const model = defineModel()
console.log(model) // customRef 对象

// defineProps(['modelValue'])
// defineEmits(['update:modelValue'])
const close = () => {
    // emit('update:modelValue', false)
    model.value = false
}

</script>

<template>
  <div class="dialog" v-if="modelValue">
    {{ modelValue }}
    <button class="close" @click="close">关闭</button>
    <h3>我是Demo3子组件</h3>
  </div>
</template>

这样写起来是不是非常方便,而且,我们可以使用defineModel()返回的Ref对象,继续v-model到其他组件上,这在我们封装自定义组件时会非常有帮助。

        接下来我们看一下,defineModel() 在多个v-model中,以及处理v-model修饰符的使用:

父组件:

<template>
  <div>
      <button @click="()=>isShow = !isShow">开关Demo3</button>
      <div>isShow: {{ isShow }}</div>
      <div>title: {{ title }}</div>
      <div>input: {{ input }}</div>
      <Demo3 v-model="isShow" v-model:title="title" v-model:input.kun="input"></Demo3>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import Demo3 from './components/Demo3.vue';

const isShow = ref<boolean>(true)
const title = ref<string>('标题')
const input = ref<string>('输入框内容')

</script>

子组件:

<script setup lang="ts">
const model = defineModel()
const title = defineModel('title', { type: String, default: '' })
// 这里 可以解构获取 ref对象 以及 修饰符对象
const [input, inputModifiers] = defineModel('input', {
    // get() 省略了 这里暂时不需要,如果需要可以在这里做些处理
    /* get(value: string) {
        return value + '鸡你太美?'
    }, */
    set(value: string) {
        // 如果使用了 .kun 修饰符,则返回处理过后的值
        if (inputModifiers.kun) {
            return value + '唱、跳、rap、篮球'
        }
        // 否则,原样返回
        return value
    }
})

const close = () => {
    model.value = false
}

</script>

<template>
  <div class="dialog" v-if="modelValue">
    {{ modelValue }}
    <button class="close" @click="close">关闭</button>
    <h3>我是Demo3子组件</h3>
    title: <input v-model="title" />
    <br>
    input: <input v-model="input" />
  </div>
</template>
<style scoped>
.dialog{
    width: 500px;
    padding: 10px;
    border: 5px solid #ccc;
    position: relative;
    overflow: auto;
}
.close{
    position: absolute;
    right: 10px;
}
</style>

  • 9
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值