【问题标题】:Vue 3 not updating inline styleVue 3 不更新内联样式
【发布时间】:2021-12-30 20:34:45
【问题描述】:

我为 vue 3 设置了一些演示代码,用于将内联样式更新为计算对象,但它没有更新。

<!DOCTYPE html>
<html>
    <head>
        <title>Demo</title>
        <link rel="stylesheet" href="main.css">
        <script src="https://cdn.jsdelivr.net/npm/vue@3.2.26/dist/vue.global.prod.min.js"></script>
    </head>

    <body>
        <div id="map">
            <div id="infantry" class="unit" :style="style">
                Position: {{ x }} {{ y }}
            </div>  
        </div>
    
        <script>
            const Infantry = {
                data() {
                    return {
                        x: 0,
                        y: 0
                    }
                },
                mounted() {
                    setInterval(() => {
                        this.x++;
                        this.y++;
                    }, 1000);
                },
                computed : {
                    style() {
                        return {
                            top : this.x
                        };
                    }
                }
            }

            Vue.createApp(Infantry).mount('#infantry');
        </script>
    </body>
</html> 

这部分不起作用

:style="style"

我检查了 dom,它没有将样式设置为使用top。有谁知道怎么回事?

【问题讨论】:

    标签: javascript html vue.js vuejs3


    【解决方案1】:

    问题是您绑定了挂载 vue 应用程序的元素的属性,然后将 px 添加到返回的顶部值:

    .unit {
      position: absolute
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Demo</title>
      <link rel="stylesheet" href="main.css">
      <script src="https://cdn.jsdelivr.net/npm/vue@3.2.26/dist/vue.global.prod.min.js"></script>
    </head>
    
    <body>
      <div id="map">
        <div class="unit" :style="style">
          Position: {{ x }} {{ y }}
        </div>
      </div>
    
      <script>
        const Infantry = {
          data() {
            return {
              x: 0,
              y: 0
            }
          },
          mounted() {
            setInterval(() => {
              this.x++;
              this.y++;
            }, 1000);
          },
          computed: {
            style() {
              return {
                top: this.x + "px"
              };
            }
          }
        }
    
        Vue.createApp(Infantry).mount('#map');
      </script>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-18
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 2021-10-03
      • 2020-03-19
      • 2022-10-14
      相关资源
      最近更新 更多