【问题标题】:Dynamically Edit Inline CSS with VueJS使用 VueJS 动态编辑内联 CSS
【发布时间】:2016-06-18 12:44:08
【问题描述】:

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

换句话说,我该怎么做 background-image: {{pic_url}};

抱歉格式化,在移动设备上。

【问题讨论】:

    标签: javascript html css vue.js


    【解决方案1】:

    我在完成这项工作时遇到了一些麻烦,因为内联样式周围有引号,然后'url("")' 中有另外两组引号。当我将样式对象拉出到它自己的对象中时,我得到了它的工作:

    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();
      }
    });
    

    【讨论】:

    • 好吧,有两个问题:为什么是:style 而不是v-style,为什么是computed 而不是methods
    • 另外,我如何更改pic_url,因为它在函数内? pic_url 最初并不为人所知,因为它是通过 GET 请求获得的。
    • :stylev-bind:style 的简写,我认为v-style 已被弃用。对于计算属性,计算属性就像数据属性一样,只是它们在使用的属性发生更改时重新计算。所以当pic_url发生变化时,backgroundStyle会自动更新
    • 至于那个,只要在你的数据函数中设置pic_url:"",然后当你检索它时你可以更新它,backgroundStyle会重新计算。
    • 那么在http请求函数中我是否只需添加this.$set('pic_url', result);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    相关资源
    最近更新 更多