Mar*_*koh 5 vue.js vue-component vuejs3 vue-composition-api
如何在 Composition API 的设置函数中引用图像?路径是“../assets/pic.png”
\n如果我直接在模板内部使用路径,作为 img 标记中的 src,图像将显示在页面上。当我检查它时,它显示图像名称,后跟 id,然后是文件扩展名,例如:\xe2\x80\x9c/img/pic.123456.png\xe2\x80\x9d。我可以这样做来得到我想要的东西,但它看起来不像是在 Vue 中做事的正确方法。
\n我\xe2\x80\x99m 认为它应该是这样的:
\n<template>\n <div>\n <img src="pic">\n </div>\n</template>\n\n\n<script>\n\nimport { ref } from 'vue'\nexport default {\n\n setup(){\n\n const pic = ref('../assets/pic.png')\n\n return { pic }\n } \n\n}\n\n</script>\n\n<style>\n\n</style>\nRun Code Online (Sandbox Code Playgroud)\n我相信它在选项 API 中会像这样工作(当然没有 \xe2\x80\x98ref\xe2\x80\x99)。我可以\xe2\x80\x99t 让它与 Composition API 一起使用。我想这可能与“id”有关。另外我如何引用数组中的图像?
\n谢谢。
\n您需要首先使用require函数请求图像,然后将返回值传递给ref。并且您应该使用v-bind绑定 src 属性。
这是基于您的代码的完整示例:
<template>
<div>
<img v-bind:src="pic">
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup(){
const pic = ref(require('../assets/pic.png'))
return { pic }
}
}
</script>
<style>
</style>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5311 次 |
| 最近记录: |