RulesProp(方法二不报错,方法一报错)
来源:5-4 ValidateInput 第三部分 — 支持 v-model
不染的卡卡
2023-12-04
方法一:
<script setup lang="ts"> import { reactive, defineProps, ref, PropType, defineEmits } from 'vue' const emailReg = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/ interface RuleProp { type: 'required' | 'email'; message: string; } export type RulesProp = RuleProp[] const props = defineProps({ rules: Array as PropType<RulesProp>, modelValue: String }) const inputRef = reactive({ val: props.modelValue || '', error: false, message: '' }) const emits = defineEmits(['update:modelValue']) const updateValue = (e: Event) => { const targetValue = (e.target as HTMLInputElement).value inputRef.val = targetValue emits('update:modelValue', targetValue) } const validateInput = () => { if (props.rules) { const allPassed = props.rules.every(rule => { let passed = true inputRef.message = rule.message switch (rule.type) { case 'required': passed = (inputRef.val.trim() !== '') break case 'email': passed = emailReg.test(inputRef.val) break default: break } return passed }) inputRef.error = !allPassed } } </script>
方法二:
<script lang="ts"> import { defineComponent, reactive, PropType } from 'vue' const emailReg = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/ interface RuleProp { type: 'required' | 'email'; message: string; } export type RulesProp = RuleProp[] export default defineComponent({ props: { rules: Array as PropType<RulesProp>, modelValue: String // 属性 }, setup(props, context) { const inputRef = reactive({ val: props.modelValue || '', error: false, message: '' }) const updateValue = (e: Event) => { const targetValue = (e.target as HTMLInputElement).value inputRef.val = targetValue context.emit('update:modelValue', targetValue) } const validateInput = () => { if (props.rules) { const allPassed = props.rules.every(rule => { let passed = true inputRef.message = rule.message switch (rule.type) { case 'required': passed = (inputRef.val.trim() !== '') break case 'email': passed = emailReg.test(inputRef.val) break default: break } return passed }) inputRef.error = !allPassed } } return { inputRef, validateInput, updateValue } } }) </script>
<template>
<div class="validate-input-container pb-3">
<input type="text" class="form-control" :value="inputRef.val" :class="{ 'is-invalid': inputRef.error }"
@blur="validateInput" @input="updateValue">
<span v-if="inputRef.error" class="invalid-feedback">{{ inputRef.message }}</span>
</div>
</template>
结果:方法二不报错,方法一报错
错误信息::
Module ‘".vue"’ has no exported member ‘RulesProp’. Did you mean to use 'import RulesProp from ".vue"’ instead
写回答
1回答
-
张轩
2023-12-05
同学你好
在 <script setup> 语法糖中,没办法再使用 export 导出任何的变量或者类型。
你可以把它们放置到单独的 ts 文件中中进行导出,或者写两个 script 标签
00