vue2 vue3 组件 v-modle 用法

100 阅读1分钟

vue2

<template>
    <view><van-uploader
        @after-read="afterRead" 
        deletable
        :file-list="fileList" multiple />
        
    </view>
</template><script>
    export default {
        name:"base-upload",
        props: {
            value:{ 
                type:Array,
                default:[],
                required: true
            },
        },
        model: {
            prop: 'value', // 默认是value
            event: 'input', // 默认是input
          },
        // emits: ['update:value'],
        data() {
            return {
                fileList:this.value,
            };
        },
        watch: {
​
            fileList: {
                immediate: true,
                handler(newVal, oldVal) {
                    // console.log(newVal,oldVal)
                    this.valueChange(newVal);
                },
            },
        },
        
        created() {
            console.log('created',this.value)
        },
        methods: {
            // 内容发生变化,进行处理
            valueChange(newVal) {
                const value = newVal;
                this.$nextTick(() => {
                    this.$emit("input", value);
                });
            },
            // 上传图片
            afterRead(file) {
                // console.log(file)
                // 此时可以自行将文件上传至服务器
                this.fileList = [...this.fileList,...file.detail.file]
            
            },
        }
    }
</script><style></style>

vue3

<template>
  <el-upload
      class="avatar-uploader"
      action="/api/Upload/upload"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :disabled="disabled"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><plus />上传照片</el-icon>
  </el-upload>
</template><script setup>
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { defineEmits, defineProps, ref } from 'vue';
​
const props = defineProps({
  modelValue: Array,
  disabled: Boolean
})
​
const emit = defineEmits(['update:modelValue'])
​
​
const imageUrl = ref(props.modelValue)
const handleAvatarSuccess = (res, file) => {
  imageUrl.value = URL.createObjectURL(file.raw)
  emit('update:modelValue', imageUrl.value)
}
​
const beforeAvatarUpload = (file) => {
​
  return true
}
</script><style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon.avatar-uploader-icon {
  font-size: 14px;
  color: #8c939d;
  width: 100%;
  padding: 0 10px;
  height: 108px;
  text-align: center;
}
.avatar {
  width: 100%;
  height: 108px;
  display: block;
  min-width: 90px;
}
</style>