index.vue 1012 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <template>
  2. <!-- 你的自定义受控组件-->
  3. <div>
  4. <el-tag :type="randomType">{{ data }}</el-tag>
  5. </div>
  6. </template>
  7. <script lang="ts" setup>
  8. import {watch, ref} from "vue";
  9. const props = defineProps({
  10. modelValue: String || Object,
  11. displayLabel: {
  12. type:String,
  13. default: ""
  14. }
  15. })
  16. // template上使用data
  17. const data = ref()
  18. watch(() => {
  19. return props.modelValue
  20. }, // 监听modelValue的变化,
  21. (value) => {
  22. if (typeof value === "string") {
  23. data.value = value
  24. } else if (typeof value === "object") {
  25. const {displayLabel} = props
  26. data.value = value ? value[displayLabel] : null
  27. } else {
  28. data.value = null
  29. }
  30. }, // 当modelValue值触发后,同步修改data.value的值
  31. {immediate: true} // 立即触发一次,给data赋值初始值
  32. )
  33. const tagType = ['success', 'info', 'warning', 'danger']
  34. const randomType = (): string => {
  35. return tagType[Math.floor(Math.random() * tagType.length)];
  36. }
  37. </script>