Search code examples
vue.jsnuxt.jscomputed-propertiescomputed-style

Vue style (background-image) binding not reactive


I want to change some part of the site based on selected language without any refresh. All worked but I have tried multiple ways to bind background-image dynamically on no refresh site language change (i18n). But no success.

<div :style="{'background-image' : mainBackground}">
     test div
</div>

I have created a computed to return currently used link based on language.

mainBackground(){
    return this.isTurkishSite ? 'url(/images/home/home_bg_main_tr.jpg);' : 'url(/images/home/home_bg_main.jpg);'
}

But after change site language by dropdown all other elements src are updated to use the selected language image file. But only this background path is not updating. Also style attribute is deleted on the element itself. I can not figure out why this solution not worked properly. Also rendered mainBackground computed into the div element. And returned link is updated based on language.

I have solved the problem by using class binding. 1 class for Turkish lang, and main class for all other languages. And used them in conditional class binding. Solution:

:class="[isTurkishSite ? 'bg-turkish' : '']"

Solution

  • It's not working because of the semicolons you put at the end of url() directives, css rules set in object notation with Vue don't require semicolons :)