Vue绑定url在image src中无法正常工作

问题描述 投票:1回答:1
<template>
  <div id="app">
    <b-container >
      <b-row>
        <div class="product">
          <img src='./assets/SocksG.jpg' alt="">
        </div>
        <div class="cart">
          <button @click="addToCart">Add To Cart</button>
          <br>
          <p>Cart({{cart}})</p>
        </div>
        <div v-for="variant in variants" 
          :key="variant.variantId"
          class="color-box"
          :style="{backgroundColor:variant.variantColor}"
          @mouseover ="updateProduct(variant.variantImage)"
          >
        </div>
      </b-row>
    </b-container>
  </div>
</template>
export default {
  name: 'App',
  data() {
    return {
      cart: 0,
      variants: [{
        variantId: 2234,
        variantColor: 'green',
        variantImage: './assets/SocksG.jpg'
      }, {
        variantId: 2235,
        variantColor: 'blue',
        variantImage: './assets/SocksB.jpg'
      }]
    }
  },
  methods: {
    addToCart() {
      this.cart += 1
    },
    updateProduct(variantImage) {
      this.image = variantImage
    }
  }
}

[起初,我将:src应用于socksG图像,并且在脚本中我不得不使用img:require("./assets/SocksG.jpg"并起作用。

现在有了应该激活@mouseover函数的updateProduct()事件处理程序,我感觉到我在应该获取variantImage的Vue url处理程序上做错了,因为当我使用Vue devtools的图像URL为img/SocksG.jpg,而不是./assets/SocksG.jpg。我在做什么错?

vue.js webpack vuejs2 vue-component vue-cli
1个回答
0
投票

image添加数据属性:

return {
   image: ...,  // Set some initial image filename here
   cart: 0,
   ...
}

像这样使用require

<img :src="require('@/assets/' + this.image)" alt="">

并从网址中删除路径:

variantImage: 'SocksG.jpg'
...
variantImage: 'SocksB.jpg'

现在图像src已绑定到this.image,您可以通过鼠标悬停进行更改。

© www.soinside.com 2019 - 2024. All rights reserved.