首页 > 其他分享 >Vue3中 v-model 语法糖运用

Vue3中 v-model 语法糖运用

时间:2022-12-08 14:33:42浏览次数:69  
标签:show Vue3 value 语法 props 组件 model modelValue

一、介绍

在 Vue 2.0 发布后,开发者使用 v-model 指令时必须使用名为 value 的 prop。如果开发者出于不同的目的需要使用其他的 prop,就不得不使用 v-bind.sync。

此外,由于 v-model 和 value 之间的这种硬编码关系的原因,产生了如何处理原生元素和自定义元素的问题。

在 Vue 2.2 中,Vue 引入了 model 组件选项,允许组件自定义用于 v-model 的 prop 和事件。但是,这仍然只允许在组件上使用一个 v-model。

在 Vue 3 中,双向数据绑定的 API 已经标准化,以减少开发者在使用 v-model 指令时的混淆,并且更加灵活。

2.x 中的语法

在 2.x 中,在组件上使用 v-model 相当于绑定 value prop 并触发 input 事件:

<template>
<div>
<div>父组件 -- {{count}}</div>
<ChildComponent v-model="count" />

<!-- 是以下的简写: -->
<!-- <ChildComponent :value="count" @input="count = $event" /> -->
</div>
</template>

<script>
import ChildComponent from '@/views/childComponent.vue';
export default {
data() {
return {
count:100,
};
},
components:{
ChildComponent
},
};
</script>
<template>
<div>
子组件
<input type="text" v-model.number="inputVal" @input="userInput">
</div>
</template>

<script>
export default {
data() {
return {
inputVal:null,
}
},
props:{
value:{
default:0,
}
},
methods: {
userInput(){
this.$emit('input',this.inputVal)
}
},
watch:{
value:{
handler(newVal,oldVal){
this.inputVal = newVal;
},
immediate:true
}
}
}
</script>

这里 v-model 实际上就是为表单元素定制的,input 事件和 value prop 都是强耦合的。

如果想要更改 prop 或事件名称,则需要在 ChildComponent 组件中添加 model 选项:

<template>
<div>
<div>父组件 -- {{count}}</div>
<ChildComponent v-model="count" />

<!-- 是以下的简写: -->
<!-- <ChildComponent :customParams="count" @change="count = $event" /> -->
</div>
</template>
<template>
<div>
子组件
<input type="text" v-model.number="inputVal" @input="userInput">
</div>
</template>

<script>
export default {
data() {
return {
inputVal:null,
}
},
model: {
prop: 'customParams',
event: 'change'
},
props:{
// 这将允许 `value` 属性用于其他用途
value: String,
// 使用 customParams 代替 value 作为 model 的 prop
customParams: {
default: 0,
}
},
methods: {
userInput(){
console.log(this.inputVal)
this.$emit('change',this.inputVal)
}
},
watch:{
customParams:{
handler(newVal,oldVal){
this.inputVal = newVal;
},
immediate:true
}
}
}
</script>

3.x 中的语法

在 3.x 中,自定义组件上的 v-model 相当于传递了 modelValue prop 并接收抛出的 update:modelValue 事件:

<template>
<div>
<div>父组件 -- {{count}}</div>
<ChildComponent v-model="count"/>

<!-- 是以下的简写: -->
<!-- <ChildComponent :modelValue="count" @update:modelValue="count = $event"/> -->
</div>
</template>

<script>
import { ref } from 'vue';
import ChildComponent from '@/components/childComponent.vue'
export default {
components:{
ChildComponent,
},
setup(){
const count = ref(100);
return {
count,
}
}
}
</script>
<template>
<div>
子组件
<input type="text" v-model.number="inputVal" @input="userInput">
</div>
</template>

<script>
import { ref, watch } from 'vue';
export default {
props:{
modelValue:{
default:0,
}
},
setup(props,{emit}) {
const inputVal = ref(null);
const userInput = () => {
emit('update:modelValue', inputVal.value)
};

watch(props,(newVal,oldVal) => {
inputVal.value = props.modelValue;
},{immediate:true})
return {
userInput,
inputVal,
}
},
}
</script>

v-model 参数

若需要更改 model 的名称,现在我们可以为 v-model 传递一个参数,以作为组件内 model 选项的替代:

<ChildComponent v-model:title="pageTitle" />

<!-- 是以下的简写: -->
<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />

Vue3中 v-model 语法糖运用_自定义

允许我们在自定义组件上使用多个 v-model

<ChildComponent v-model:title="pageTitle" v-model:content="pageContent" />

<!-- 是以下的简写: -->

<ChildComponent
:title="pageTitle"
@update:title="pageTitle = $event"
:content="pageContent"
@update:content="pageContent = $event"/>

v-model 修饰符

除了像 .trim 这样的 2.x 硬编码的 v-model 修饰符外,现在 3.x 还支持自定义修饰符:

<ChildComponent v-model.capitalize="pageTitle" />

示例

Vue3中 v-model 语法糖运用_开发者_02


如果我们将:show="show"通过父组件传到子组件,但很快发现子组件只能读show值,而不能更改

Vue3中 v-model 语法糖运用_开发者_03

父组件

<template>
<div class="parent">
<Children v-if="show" :show="show" ></Children>
<div class="float">
<button @click="show = !show">{{ show ? "关闭" : "开启" }}</button>
<div>show的值{{ show }}</div>
</div>
</div>
</template>

<script setup>
import { ref } from 'vue';
import Children from './Children.vue';
let show = ref(true);
</script>

子组件

<template>
<div class="children">
<button @click="close">
关闭
</button>
</div>
</template>

<script setup>
let props = defineProps(['show'])

const close = () => {
props.show= false;
}
</script>

当然,你可以在父组件传递给子组件一个自定义事件,通过子组件回调改变show值,那如果是多个值都需要修改呢,这样就显得繁琐了

而有了v-model,这一切都显得简单了

父组件
<Children v-if="show" v-model="show" ></Children>

子组件
<template>
<div class="children">
<button @click="close">
关闭
</button>
</div>
</template>

<script setup>
let props = defineProps(['modelValue'])
let emits = defineEmits(['update:modelValue'])

const close = () => {
console.log(props, emits)
emits('update:modelValue', false);
}
</script>

我们只需要emits这个update:modelValue事件,就可以修改show值

此外,默认情况下值名称是modelValue,我们可以自定义多个值

父组件
<Children v-if="show" v-model="show" v-model:test="test" ></Children>

子组件
<template>
<div class="children">
<button @click="close">
关闭
</button>
</div>
</template>

<script setup>
let props = defineProps(['modelValue','test'])
let emits = defineEmits(['update:modelValue','update:test'])

const close = () => {
console.log(props, emits)
emits('update:modelValue', false);
}
</script>

Vue3中 v-model 语法糖运用_开发者_04

其实这也是一个简单的父子组件传值和事件,只是v-model把它们进行了简单包装了

点击查看父子组件样式

/* 父组件 */
.parent {
width: 100vw;
height: 300px;
display: flex;
background-color: orange;
justify-content: center;
align-items: center;
}
.float{
position: absolute;
top: 0;
display: flex;
color: black;
flex-direction: row;
width: 30vw;
justify-content: space-around;
left: 50%;
transform: translateX(-50%);
}

/* 子组件 */
.children {
background-color: yellow;
width: 70vw;
height: 200px;
}

​官方文档 v-model的使用​​学习Vue3 第二十六章(深入v-model)

箴言:因为这些东西是非常简单的。不要抱怨自己学不会,那是因为你没有足够用心。



标签:show,Vue3,value,语法,props,组件,model,modelValue
From: https://blog.51cto.com/echohye/5921256

相关文章

  • spring mvc中modelattribute和sessionatrribute
    摘自http://tengj.top/2016/05/02/springmvcyuanli/SpringMVC支持使用@ModelAttribute和@SessionAttributes在不同的模型和控制器之间共享数据......
  • vue3中ref和reactive的区别
    ref和reactive都是用来定义响应式数据的。ref允许我们创建一个任意类型的响应式的ref对象,在使用时需要带上.value在模板中使用ref对象时,假如ref位于顶层,就不需要使......
  • vue3 Cropperimage插件写入默认网络图片跨域解决办法----- 图片转换成base64
    最近项目中有一个裁切图片的需求,百度了一番最后选用cropperImage插件。由于项目中图片是存放在阿里云上,cropperImage插件在初始化默认图的时候会存在跨域问题,百度经验我选......
  • C++的语法 学习笔记1
    C++的语法学习笔记1  C++各种数据类型的默认值数值类型int/double/float/long0char'\0'string"\0"bool0,也就是false  数......
  • python之路44 jQuery语法应用 与Bootstrap框架
    写的略粗糙咨询https://www.cnblogs.com/Dominic-Ji/p/10490669.html作业讲解页面简陋定时器:<inputtype="text"id="d1"><buttonid="startBtn">开始</button><bu......
  • shell编程时出现:未预期的符号 `then' 附近有语法错误 或者 : 行 : `then'
    #!/bin/bashcd/var/logsum=0foriin`ls-r*`do       if[-f$i];then       letsum++       echo"文件名:$i"......
  • smail基本语法示例
    准备工作工欲善其事必先利其器,所以要学好smail语法,好的工具是必须的,这里推荐两个工具,一个是Smali2Java,也就是将smail文件转换成java的工具;另一个工具是J2S2J1.3,这个工具可......
  • VBA-语法-Type结构体
    VBA中结构体不能定义在函数或者过程中,要定义在模块中,否则会提示无效内部过程,或者类型未定义定义:TypePersonpNameAsStringpAgeAsByteEndType使用:Di......
  • Agileboot 1.6.0 发布啦 - 一款致力于规范/精简/可维护 的Springboot + Vue3的快速开
    ⚡平台简介⚡AgileBoot是一套开源的全栈精简快速开发平台,毫无保留给个人及企业免费使用。本项目的目标是做一款精简可靠,代码风格优良,项目规范的小型开发脚手架。适合个人......
  • Java基础语法
    1.注释​ 注释是对代码的解释和说明文字。Java中的注释分为三种:单行注释://这是单行注释文字多行注释:/*这是多行注释文字这是多行注释文字这是多行注释文字......