html 如何在Background-image:url中调用vue.js对象

py49o6xq  于 2023-04-18  发布在  Vue.js
关注(0)|答案(1)|浏览(153)

我有这个div,它使用background-image url渲染图像,下面的第一个代码在静态方式下工作正常

工作正常

<div class="image-input-wrapper" style="background-image:url(/storage/images/validations/my_main_image.png)"></div>

但是当我像下面的代码一样根据obj来设置图像的值时,它不起作用

不工作

<div class="image-input-wrapper" style="background-image:url('/storage/images/validations/'+emvdetailsdata[0].card_image)"></div>

在我的第二个例子中有没有实现错误?

vuejs

module.exports = function(data) {
  var _data = {
      config: null,
      n: 1,
      emvdetailsdata: Object,
};
return{
 data: (() => Object.assign({}, data, _data)),
    props: {
        data_object: Object,
    },
    mounted() {
        this.init();
 },
methods:{
  init(){
    this.functionexample();
  }
}

functionexample(){
   this.emvdetailsdata = objt["emv"];
}}
dwbf0jvd

dwbf0jvd1#

如果你想让Vue计算一些属性,那么你需要绑定它。

v-bind:style="...

:style="..

如果你不这样做,你的样式属性将只有你传递给它的文本。
这个

style="background-image:url('/storage/images/validations/'+emvdetailsdata[0].card_image)"

应改为

:style="'background-image:url(\'/storage/images/validations/\'' + emvdetailsdata[0].card_image + ')'"

或使用JS Template literals (Template strings)

:style="`background-image:url('/storage/images/validations/${emvdetailsdata[0].card_image})`"
const { createApp, ref } = Vue
const App = {
  setup() {
    const emvdetailsdata = ref([ { card_image: 'https://3.bp.blogspot.com/-f2XX6_CJNNc/VCaHU7fHwJI/AAAAAAAAGig/ORo4Kah5u-Q/s1600/simple-gray-texture.jpg' } ]);
    return { emvdetailsdata }  
  }
}
const app = createApp(App)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app">
  <div style="background-image:url(emvdetailsdata[0].card_image)">div 1</div>
  <div :style="'background-image:url(' + emvdetailsdata[0].card_image + ')'">div 2</div>
  <div :style="`background-image:url(${emvdetailsdata[0].card_image})`">div 3</div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

相关问题