6

How can I change an attribute of a tag with VueJS? I'm trying to make a one-page app with a background that changes every time it fetches data from a backend. I've tried using the v-bind:style and v-style but both ended up "breaking" Vue. Is there a way I can just write a method like you can in native JS that changes the DOM? I also tried implementing a document.getElementbyId so and and so forth but it also wrecked VueJS.

In other words, how can I do background-image: {{pic_url}};

Sorry for formatting, on mobile.

1 Answer 1

5

I had some trouble getting this working because there are quotes around the inline style, then two more sets of quotes in 'url("")'. When I pulled the style object out into its own object I got it working:

https://jsfiddle.net/ahwLc3rq/

html

<div id="app">
  <div id="test" :style="backgroundStyle"></div>
</div>

js

new Vue({
    el:'#app',
  data:function(){
    return {
        pic_url: 'https://anchormetrics.com/wp-content/themes/bootstrap-basic-child/images/amlogo.png'
    }
  },
  computed:{
   backgroundStyle:function(){
    return {
        'background-image':'url("'+this.pic_url+'")'
    }
   }
  },
  methods:{
    fetchPic:function(){
      this.$http.get('/path/to/api').then(function(response){
        this.pic_url = response;
      }.bind(this))
    }
  },
  ready:function(){
    this.fetchPic();
  }
});
Sign up to request clarification or add additional context in comments.

11 Comments

Ok so two question: Why :style instead of v-style, and why computed instead of methods?
And also, how do I change pic_url since it is within the function? pic_url isn't known at first as it's acquired through a GET request.
:style is shorthand for v-bind:style and I think v-style is deprecated. As for computed, computed properties are just like data properties except they re-compute anytime a property they use is changed. So when pic_url changes, backgroundStyle will automatically update
As for that, just set pic_url:"" in your data function and then when you retrieve it you can update it and backgroundStyle will re-compute.
So in the http request function would I just add this.$set('pic_url', result);?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.