Vue2.0中动态拼接图片路径

本地资源图片路径我们用require的方法解决

外部资源(来自服务器的图片)我们如果使用以下方式则无法找到对应图片,会把变量当成字符直接处理

<div class="first-img"><img src='http://81.70.162.221:3000/${blog.image}' alt="" /></div>

使用场景:获取后端返回的图片资源并渲染到页面上

解决方法:

<template>
    <div class="first-img"><img :src="getImgUrl(content.image)" alt="" /></div>
</template>

<script>
export default {
  data() {
    return {
      content: [],
    };
  },
  created() {
    this.getArticle();
  },
  methods: {
    getArticle() {
      this.axios
        .get("/getBlog", {
          params: {
            id: this.$route.query.id,
          },
        })
        .then((res) => {
          this.content = res.data;
        });
    },
    getImgUrl(img) {
      return "http://81.70.162.221:3000/" + img;
    },
  },
};
</script>

getImgUrl方法拼接好路径并返回

猜你喜欢

转载自blog.csdn.net/weixin_52479225/article/details/126623988