[Vuejs]-How to change style of an element based on window width in Vue

0👍

Try to use computed to check your width data changes.

I changed your code this way

export default {
  data() {
    return {
      window: {
        width: 0,
      },
    },
    computed: {
      bgImage() {
        if (this.width < 500) {
          return {
            backgroundImage: `linear-gradient(to bottom,rgba(245, 246, 252, 0) 45%,rgb(0, 0, 0) 100%), url(${this.hero.image})`
          }
        } else {
          return {
            backgroundImage: `url(${this.hero.image})`
          }
        }
      }
    }

    created: function() {
        window.addEventListener('resize', this.handleResize);
      },
      destroyed: function() {
        window.removeEventListener('resize', this.handleResize);
      },
      methods: {
        handleResize() {
          this.width = window.innerWidth;
        }
      },
  };

Leave a comment