<template>
  <div>
    <form @submit.prevent="uploadImage">
      <label for="image">请选择一个图像:</label>
      <input type="file" id="image" ref="image" accept="image/*" @change="previewImage">
      <button type="submit">上传</button>
    </form>
    <img v-if="previewUrl" :src="previewUrl" alt="预览图" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      previewUrl: '', // 预览图片的DataURL
    }
  },
  methods: {
    async uploadImage() {
      // 上传图片的逻辑
    },
    async previewImage() {
      const file = this.$refs.image.files[0]
      if (file) {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.previewUrl = reader.result
        }
      }
    },
  },
}
</script>
<p>在 input 标签上添加一个 change 事件监听器,获取用户选择的图片,并将其转换为 DataURL,然后在页面上添加一个 img 标签,将 DataURL 设置为 img 的 src 属性值,从而实现图片的预览功能。具体代码如下:</p>
<pre><code>&lt;template&gt;
  &lt;div&gt;
    &lt;form @submit.prevent=&quot;uploadImage&quot;&gt;
      &lt;label for=&quot;image&quot;&gt;请选择一个图像:&lt;/label&gt;
      &lt;input type=&quot;file&quot; id=&quot;image&quot; ref=&quot;image&quot; accept=&quot;image/*&quot; @change=&quot;previewImage&quot;&gt;
      &lt;button type=&quot;submit&quot;&gt;上传&lt;/button&gt;
    &lt;/form&gt;
    &lt;img v-if=&quot;previewUrl&quot; :src=&quot;previewUrl&quot; alt=&quot;预览图&quot; /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  data() {
    return {
      previewUrl: '', // 预览图片的DataURL
    }
  },
  methods: {
    async uploadImage() {
      // 上传图片的逻辑
    },
    async previewImage() {
      const file = this.$refs.image.files[0]
      if (file) {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () =&gt; {
          this.previewUrl = reader.result
        }
      }
    },
  },
}
&lt;/script&gt;
</code></pre>
Vue.js 前端图片上传预览功能实现

原文地址: https://www.cveoy.top/t/topic/nsjj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录