前端 Vue 通用组件

通用图片上传 Vue 组件

// <upload-image v-model="item" />

// 图片上传组件
Vue.component('UploadImage', {
    data: () => ({eid: '', mclass: 'layui-show'}),
    model: {prop: 'image', event: 'change'},
    props: {
        image: {type: String, default: ''},
        showinput: {type: Boolean, default: true}
    },
    template:
        '<div class="relative">' +
        '   <input class="layui-input layui-bg-gray" :class="mclass" v-model="image" readonly :id="eid" placeholder="请上传图片">' +
        '   <a class="input-right-icon" :class="mclass" data-type="jpg,png,gif" :data-upbtn="eid"><i class="layui-icon layui-icon-upload"></i></a>' +
        '</div>',
    created() {
        if (this.showinput === false) this.mclass = 'layui-hide';
        this.eid = Math.random().toString().replace('0.', 'upimg-');
    },
    watch: {
        image() {
            this.$nextTick(() => $('#' + this.eid).trigger('change'));
        }
    },
    mounted() {
        this.$nextTick(() => {
            let $ele = $('#' + this.eid).uploadOneImage();
            $ele.on('change', e => this.$emit('change', e.target.value));
            $('[data-upbtn=' + this.eid + ']').uploadFile(src => $ele.val(src).trigger('change'));
        });
    }
});

其他案例代码

use think\admin\Storage;

// 抓取内容的 base64 图片并上传到云端
$content = preg_replace_callback('/"data:image\/([a-zA-Z]+);base64,(.*)"/', function ($matches) {
    return '"' . Storage::saveImage(trim($matches[0], '"'))['url'] . '"';
}, $content);
Last Updated:
Contributors: 邹景立