使用VueJS动态编辑内联CSS

dud*_*aw3 6 html javascript css vue.js

如何使用VueJS更改标签的属性?我正在尝试创建一个单页应用程序,其背景在每次从后端获取数据时都会发生变化.我尝试过使用它v-bind:style,v-style但最终都"打破"了Vue.有没有办法我可以在原生JS中编写一个更改DOM的方法?我也尝试过实现document.getElementbyId等等,但它也破坏了VueJS.

换句话说,我该如何做背景图像:{{pic_url}};

对不起格式化,在手机上.

Jef*_*eff 5

我在使用这个工作时遇到了一些麻烦,因为有内联样式的引号,然后是两组引号'url("")'.当我将样式对象拉出到自己的对象中时,我得到了它的工作:

https://jsfiddle.net/ahwLc3rq/

HTML

<div id="app">
  <div id="test" :style="backgroundStyle"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

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();
  }
});
Run Code Online (Sandbox Code Playgroud)

  • `:style`是`v-bind:style`的简写,我认为`v-style`已被弃用.至于计算,计算属性就像数据属性一样,除非它们在他们使用的属性发生变化时重新计算.所以当`pic_url`改变时,`backgroundStyle`会自动更新 (2认同)