M
M
MiMarch2017-07-08 23:08:42
Vue.js
MiMarch, 2017-07-08 23:08:42

How to update styles?

The style is simply taken from data and does not change in place with it. What to do to start working?

<div v-bind:style="{background: 'url('+ photos[currentSlide]+ ')'}" id="slider"></div>

var photos = {
      0:'i.jpeg',
      1:'i2.jpeg',
      2:'i3.jpg'
    };


    var app = new Vue({
      el: '#slider',
      data: {
        currentSlide: 0,
        photos: {
          0:'i.jpeg',
          1:'i2.jpeg',
          2:'i3.jpg'
        }
      },
      methods: {
          changeSlideNext: function() {
            if(currentSlide == 2){
              currentSlide = 0;
            }
            else currentSlide++;
            this.el.style.backgroundImage = "url("+photos[currentSlide]+")"
          },
          changeSlidePrev: function() {
            if(currentSlide == 0){
              currentSlide = 2;
            }
            else currentSlide -= 1;
            this.el.style.backgroundImage = "url("+photos[currentSlide]+")"
          }
        }
      });

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2019-06-14
@MiMarch

if(currentSlide == 2){

Forgot this. Not only here - everywhere where you access currentSlide inside methods.
this.el.style.backgroundImage = ...

But this is superfluous (and this property is called a little differently ). You shouldn't work with the DOM directly; in addition, background is already assigned in your template - that's where it should be replaced with backgroundImage.
photos: {

It's better to make it an array, it's much easier.
https://jsfiddle.net/k9fqha3u/

V
Vladimir Zhosan, 2017-07-08
@iaskivsky

<div :style=`background: url(${photos[currentSlide]})` id="slider"></div>

E
Evgeny Kulakov, 2017-07-09
@kulakoff Vue.js

You can try to do something like: Further in the code:

computed: {
  styleObject: function() {
   return {
     background: `url(${this.photos[this.currentSlide]})`
   }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question