场景复现

原文的一些知识就不多做介绍了,有兴趣的移步原文即可。

介绍一下我的场景,当当当当~~~~~

这里有一个二次封装 el-input 的组件 Comp.vue,因为playground 不能使用导入类型使用,所以仅保留了 modalValue 这一个属性。

<template>
  <div>
    <component :is="h(ElInput, $props, slots)" ref="inputRef"></component>
  </div>
</template>

<script lang="ts" setup>
import { type ExtractPublicPropTypes, ref, h, useAttrs, mergeProps, useSlots } from 'vue'
import { ElInput } from 'element-plus';

type InputProps = ExtractPublicPropTypes<{ modelValue: any }> & {};
const props = withDefaults(defineProps<InputProps>(), {})
const slots = useSlots();
const attrs = useAttrs();
// 以下两种方式都是会丢失响应性的,要将右侧值放到模板里面做解构
const $props = mergeProps(attrs, props)
// const $props = { ...attrs, ...props }

const inputRef = ref()

defineExpose({
  inputRef,
})
</script>

Comp.vue 放在 App.vue 中使用

<template>
  <div>
    <Comp ref="CompEl" v-model="modelVal" />
  </div>
</template>

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

const CompEl = ref();
const modelVal = ref('ethan')
setTimeout(() => {
  console.log(222222,CompEl.value.inputRef)
  CompEl.value.inputRef?.clear()
  console.log('after clear: ', modelVal.value)
}, 1000)
</script>

主要的功能就是外部调用 el-input 的清空的方法 clear,以达到一秒后清除输入框内容的效果。结果值是被清空了,但是输入框的值没有变!这你能忍?我反正是忍不了!

image.png

关键在这

我排查了好一会发现了关键!在下面两种定义 props 的方式中,先定义,之后再拿到模板里去使用,v-model 值变了, 单视图就不会变!!

// 以下两种方式都是会丢失响应性的,要将右侧值放到模板里面做解构
const $props = mergeProps(attrs, props)
// const $props = { ...attrs, ...props }

如果拿赋值右边的值去作为props,一切正常!

<template>
  <div>
    <component :is="h(ElInput, mergeProps(attrs, props), slots )" ref="inputRef"></component>
  </div>
</template>

当然这无关动态组件,el-inputv-bind 也是无效的!

<template>
  <div>
    <el-input v-bind="$props" ref="inputRef"></el-input>
  </div>
</template>

element-plus playground 复现地址

睡了睡了

原因暂时没去深究,看有没有同僚给我解惑

夜已深,我欲入眠!文章就写到这,后面找到原因了再续上。

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]