You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中v-html无法渲染Vuetify v-img组件求助

问题原因

v-html仅能渲染普通HTML内容,Vue不会编译、解析其中的Vue组件标签。你写的<v-img>是Vuetify提供的Vue组件,被v-html插入后只会被当作无意义的自定义标签,不会被Vue实例化,因此无法正常渲染出图片。

解决方案

方案1:用渲染函数动态创建v-img组件

将图片配置转为数据,通过Vue渲染函数生成v-img组件并挂载:

<template>
  <v-card>
    <v-card-title>2</v-card-title>
    <div ref="imgContainer"></div>
  </v-card>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
  name: "slot2",
  data() {
    return {
      imgProps: {
        lazySrc: "https://picsum.photos/id/11/10/6",
        maxHeight: 150,
        maxWidth: 250,
        src: "https://picsum.photos/id/11/500/300"
      }
    };
  },
  mounted() {
    const imgComponent = new Vue({
      render: h => h("v-img", { props: this.imgProps })
    });
    imgComponent.$mount(this.$refs.imgContainer as HTMLElement);
  }
});
</script>

方案2:直接使用原生img标签(轻量场景)

如果不需要v-img的懒加载过渡、占位符等高级特性,用原生img模拟样式即可:

<template>
  <v-card>
    <v-card-title>2</v-card-title>
    <div v-html="test"></div>
  </v-card>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
  name: "slot2",
  data() {
    return {
      test: `<img 
              loading="lazy"
              style="max-height:150px;max-width:250px;"
              src="https://picsum.photos/id/11/500/300"
              alt=""
            >`
    };
  },
});
</script>

方案3:编译字符串模板(Vue2专属)

若必须保留字符串模板形式,可通过Vue.compile将模板编译为渲染函数,再通过动态组件渲染:

<template>
  <v-card>
    <v-card-title>2</v-card-title>
    <component :is="renderImg"></component>
  </v-card>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
  name: "slot2",
  computed: {
    renderImg() {
      const template = `<v-img
              lazy-src="https://picsum.photos/id/11/10/6"
              max-height="150"
              max-width="250"
              src="https://picsum.photos/id/11/500/300"
            ></v-img>`;
      const { render } = Vue.compile(template);
      return { render };
    }
  },
});
</script>

内容的提问来源于stack exchange,提问作者sha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:54:31