最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically Edit Inline CSS with VueJS - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Mar 4, 2016 at 17:02 dude0faw3dude0faw3 1291 silver badge9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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/ahwLc3rq/

html

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

js

new Vue({
    el:'#app',
  data:function(){
    return {
        pic_url: 'https://anchormetrics./wp-content/themes/bootstrap-basic-child/images/amlogo.png'
    }
  },
  puted:{
   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();
  }
});
发布评论

评论列表(0)

  1. 暂无评论