【问题标题】:Bound image not displaying in Vue project绑定图像未在 Vue 项目中显示
【发布时间】:2021-04-30 01:24:10
【问题描述】:

我有一个显示图像的组件:

<template>
    <div>
        <img :src="image" />
    </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    image: String
  }
}
</script>

当我尝试使用它并绑定图像路径时:

<MyComponent
    image="./assets/image-test.png">
</MyComponent>

但它不会显示图像。

我尝试了什么?

我尝试替换组件中的代码以直接引用图像。如果我执行以下操作,则图像会显示:

<img src="@/assets/image-test.png" />

(仅限@符号)

我尝试将绑定到组件的路径替换为:

image="@/assets/image-test.png">

但这没什么区别。

我找到了this 的答案,所以尝试了这个:

<div>
    <img :src="getImage(image)" />
</div>

  methods: {
    getImage(path) {
      return require(path);
    }
  }

在组件内部。这会导致运行时出错:

找不到模块'./assets/image-test.png'

完整的堆栈跟踪:

runtime-core.esm-bundler.js?5c40:217 Uncaught Error: Cannot find module './assets/image-test.png'
    at webpackEmptyContext (eval at ./src/components sync recursive (app.js:1080), <anonymous>:2:10)
    at Proxy.getImage (MyApp.vue?059c:17)
    at Proxy.render (MyApp.vue?059c:3)
    at renderComponentRoot (runtime-core.esm-bundler.js?5c40:710)
    at componentEffect (runtime-core.esm-bundler.js?5c40:4193)
    at reactiveEffect (reactivity.esm-bundler.js?a1e9:42)
    at effect (reactivity.esm-bundler.js?a1e9:17)
    at setupRenderEffect (runtime-core.esm-bundler.js?5c40:4176)
    at mountComponent (runtime-core.esm-bundler.js?5c40:4134)
    at processComponent (runtime-core.esm-bundler.js?5c40:4094)

我也用@符号尝试过。

请有人指出我正确的方向。我意识到 Vue 图像有一些怪癖(链接的帖子中这么说),但我不知道如何说服它绑定图像。

【问题讨论】:

  • 图片是否已托管在服务器上的/assets 目录中?还是要通过 Webpack 等构建管道处理?
  • 它已经托管在服务器上——在这种特殊情况下,它就是我现在的桌面
  • 你在使用 webpack 吗?请在您的帖子中更新它
  • 或 vue.config.js
  • 你有没有尝试像&lt;img src="../../assets/image-test.png"&gt;一样给出图像的路径?

标签: javascript vue.js


【解决方案1】:

图像应该在父组件中是必需的,并在脚本部分中定义才能被转译:

家长

<template>
  <div id="app">
    <MyComponent :image="img" />
  </div>
</template>

<script>
import MyComponent from "./components/MyComponent.vue";

export default {
  name: "App",
  data: () => ({
    img: require("@/assets/logo.png"),
  }),
  components: { MyComponent },
};
</script>

我的组件

<template>
  <div>
    <img :src="image" />
  </div>
</template>

<script>
export default {
  name: "MyComponent",
  props: {
    image: String,
  },
};
</script>

如果您将require 放在模板部分,您将收到类似

的错误

错误:/src/assets/logo.png 尚未转译。

【讨论】:

    猜你喜欢
    • 2020-04-10
    • 2019-09-29
    • 1970-01-01
    • 2020-06-11
    • 2021-02-17
    • 1970-01-01
    • 2019-12-27
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多