如何在 Vue 3 的 Composition API 的 Setup 函数中引用图像?

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>\n
Run Code Online (Sandbox Code Playgroud)\n

我相信它在选项 API 中会像这样工作(当然没有 \xe2\x80\x98ref\xe2\x80\x99)。我可以\xe2\x80\x99t 让它与 Composition API 一起使用。我想这可能与“id”有关。另外我如何引用数组中的图像?

\n

谢谢。

\n

Ayo*_*yat 2

您需要首先使用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)