vue3 组件v-model 以及自定义修饰符

一、 用法

在这里插入图片描述

<template>
   <div class="page-view">
      <div>
        isShow: {{ isShow }}
        <button @click="isShow = !isShow">改变isShow</button>
        inputValue: {{ inputValue }}
      </div>
    </div>
    <!-- 在vue3中v-model是props和emit的结合 -->
    <!-- 	默认提供修饰符
      v-model.trim(去掉两端空格)
      v-model.number(只输入number)
      v-model.lazy(change事件触发) -->
    <ComponentModel v-model:inputValue.isModifiers="inputValue" v-model="isShow"></ComponentModel>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted} from 'vue'
import ComponentModel from '../components/ComponentModel.vue'
const isShow = ref<boolean>(true)
const inputValue = ref<string>('请输入表单数据')
</script>
<style scoped lang="less">
.page-view{
  padding: 10px;
  button{
    width: 140px;
    height: 40px;
    border: 1px solid #ccc;
  }
}
</style>

在这里插入图片描述

<template>
  <div v-if="modelValue" class="component-model">
    <h1>子组件</h1>
    <div class="content">
      <span>显示父组件数据modelValue: {{ modelValue }}</span>
      <button @click="changeIsShow"> 改变父组件isShow</button>
      <div>
        内容:<input type="text" :value="inputValue" @input="changeInputValue">
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { emit } from 'process';
import { ref, reactive, toRefs, onMounted} from 'vue'
const props = defineProps<{
  modelValue: boolean,
  inputValue: string,
  inputValueModifiers?: {  //命名默认Modifiers  如有参数model + Modifiers   
    isModifiers: boolean  //自定义修饰符
  }
}>()
// defineProps({
//   modelValue: Boolean,
//   inputValue: String
// })
const emits = defineEmits(['update:modelValue', 'update:inputValue'])
const changeIsShow = () => {
  emits('update:modelValue', false)
}
const changeInputValue = (e:Event) => {
  const target = e.target as HTMLInputElement
  emits('update:inputValue', props?.inputValueModifiers?.isModifiers ? target.value + '无自定义修饰符' : target.value)
}
</script>
<style scoped lang="less">
.component-model{
  border: 2px solid #ccc;
  margin: 10px;
  padding: 10px;
  font-size: 24px;
  button{
    width: 140px;
    height: 40px;
    border: 1px solid #ccc;
    background-color: skyblue;
  }
}
</style>

二、原理

	通过el初始化赋值

在这里插入图片描述

addEventListener监听

在这里插入图片描述

在这里插入图片描述
结合emit和props更新
读取props->获取emits
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值