hello world欢迎来到前端的新世界
当前文章系列专栏:Vue.js
博主在前端领域还有很多知识和技术需要掌握,正在不断努力填补技术短板。(如果出现错误,感谢大家指出)
感谢大家支持!您的观看就是作者创作的动力
绑定单个v-model,并且使用modelValue接收,是匿名的,也可以命名,看第二种方法
父组件
<template>
<div>
<MyInput ref="myinput" v-model="valueKey"></MyInput>
{{valueKey}}
<button @click="click1">nn</button>
</div>
</template>
<script setup lang="ts">
import MyInput from "@/model/Myinput.vue";
import { ref } from "vue";
let myinput = ref(null)
let valueKey = ref("传递");
let click1 = ()=>{
myinput.value.params();
}
</script>
<style lang="less" scoped>
</style>
子组件
<template>
<div>
<input type="text" v-model="val" @input="Editval">
</div>
</template>
<script setup lang="ts">
import {ref} from "vue";
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
let val = ref(props.modelValue)
let timer = null;
const Editval = (e:Event)=>{
emit('update:modelValue',(e.target as HTMLInputElement).value)
}
</script>
<style lang="less" scoped>
</style>
总结:父组件正常传递,子组件通过modelValue来接受,然后使用emit(“update:modelValue”,参数)来修改
绑定多个v-model
父组件
<template>
<div>
<MyInput v-model:valueKey="valueKey" v-model:valueIndex="valueIndex"></MyInput>
key:{{valueKey}}
<br>
index:{{valueIndex}}
<br>
</div>
</template>
<script setup lang="ts">
import MyInput from "@/model/Myinput.vue";
import { ref } from "vue";
let valueKey = ref("传递");
let valueIndex = ref("aaaa");
</script>
<style lang="less" scoped>
</style>
子组件
<template>
<div>
<input type="text" v-model="val" @input="Editval" />
<input type="text" v-model="ind" @input="Editind" />
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const props = defineProps(["valueKey", "valueIndex"]);
const emit = defineEmits(["update:valueKey", "update:valueIndex"]);
let val = ref(props.valueKey);
let ind = ref(props.valueIndex);
let timer = null;
const Editval = (e: Event) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
emit("update:valueKey", (e.target as HTMLInputElement).value);
}, 500);
};
const Editind = (e: Event) => {
emit("update:valueIndex", (e.target as HTMLInputElement).value);
};
</script>
<style lang="less" scoped></style>
总结:多个v-model可以使用: 来进行一个命名,然后子组件接收
子组件的修改valueKey的值我是采用了一个防抖函数
如果只有一个匿名v-model的传递的话,可以使用vue3.3新添加的编译宏,defineModel来使用
注意:因为defineModel的实现属性在vue3默认中是关闭的需要配置在vite.config.ts文件中配置,vue()里面配置为defineModel配置为true
export default defineConfig({
plugins: [vue({
script:{
defineModel:true
}
})],
})
父组件
<template>
<div>
<MyInput v-model="valueKey"></MyInput>
key:{{valueKey}}
</div>
</template>
<script setup lang="ts">
import MyInput from "@/model/Myinput.vue";
import { ref } from "vue";
let valueKey = ref("传递");
</script>
<style lang="less" scoped>
</style>
子组件
<template>
<div>
<input type="text" v-model="val"/>
</div>
</template>
<script setup lang="ts">
let val = defineModel()
</script>
<style lang="less" scoped></style>
创作不易,要是本文章对广大读者有那么一点点帮助 不妨三连支持一下,您的鼓励就是博主创作的动力