请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

defineModel

<template>
  <div class="y-collapse"><slot /></div>
</template>

<script setup lang="ts">
import { provide } from "vue";
import { collapseContextKey } from "./types";
import type { CollapseProps, NameType } from "./types";
defineOptions({ name: "YCollapse", inheritAttrs: false });
const props = defineProps<CollapseProps>();
const activeNames = defineModel<NameType[]>();

if (props.accordion && activeNames.value.length > 1) {
  console.warn("accordion mode should only have one active item");
}

const handleItemClick = (item: NameType) => {
  if (props.accordion) {
    activeNames.value = [activeNames.value[0] === item ? "" : item];
  } else {
    const index = activeNames.value.indexOf(item);
    if (index > -1) {
      activeNames.value.splice(index, 1);
    } else {
      activeNames.value.push(item);
    }
  }
};

provide(collapseContextKey, {
  activeNames,
  handleItemClick,
});
</script>

老师我改成这样后,activeNames报错了,
provide那报错Type ‘ModelRef<NameType[] | undefined, string>’ is not assignable to type ‘Ref<NameType[]>’.
Types of property ‘value’ are incompatible.
Type ‘NameType[] | undefined’ is not assignable to type ‘NameType[]’.
Type ‘undefined’ is not assignable to type ‘NameType[]’.ts-plugin(2322)
types.ts(16, 3): The expected type comes from property ‘activeNames’ which is declared here on type ‘CollapseContext’

其它地方报错’activeNames.value’ is possibly ‘undefined’.
老师能麻烦你给一个全一点的代码吗

正在回答 回答被采纳积分+3

2回答

张轩 2024-05-14 09:48:29

同学你好

这是我的修改如图,不会报错,也没有问题,完美运行,

主要就是修改为

const activeNames = defineModel<NameType[]>({ required: true })

如果你还会出现类似的类型问题,可以删除 node_modules 重新 npm install 一次

https://img1.sycdn.imooc.com/szimg/6642c2cd093a4e5014960642.jpg

0 回复 有任何疑惑可以回复我~
  • 提问者 qq_慕圣1562754 #1
    感谢老师,我删除了node_modules重新install后,就可以了,感谢!
    回复 有任何疑惑可以回复我~ 2024-05-14 13:43:15
张轩 2024-05-12 09:54:17

同学你好

这里做个简单修改,设置 modelValue 为必选试试看:

const activeNames = defineModel<NameType[]>({ required: true })

其他都和你一样的,并没有额外的报错。

我装了最新版本的 vue 3.4.27 并没有出现这个错误,感觉是这两个类型已经兼容了

'ModelRef<NameType[] | undefined, string>’ is not assignable to type ‘Ref<NameType[]>’.'

你把代码(git)给我发一份吧,我在本地帮你调试一下看看。

0 回复 有任何疑惑可以回复我~
  • 提问者 qq_慕圣1562754 #1
    好的,老师,下面是我的代码git连接,麻烦老师抽空帮我调试一下,谢谢!
    https://github.com/tail1231/y_element.git
    文件路径:src\components\Collapse\Collapse.vue
    回复 有任何疑惑可以回复我~ 2024-05-13 11:22:17

相似问题

登录后可查看更多问答,登录/注册

问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信