Vue.js-更改div元素的大小,el.style.attr不起作用

时间:2019-08-21 08:35:27

标签: javascript vue.js

我试图使某物像Vue中的图像,但是在更改div元素大小时遇到​​麻烦。

圈子组:

Vue警告:

  

挂接的钩子中出现错误:“ TypeError:无法读取未定义的属性'style'

"

也尝试了el.setAttribute("style", "top: px; bottom: px;..."),但setAttribute()方法存在错误。

<template>
  <div class="wavyCircles">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
  </div>
</template>

computed: {
    circleSizing() {
      let circles = document.getElementsByClassName("circle")
      for (let i = 0; i <= circles.length; i++) {
        circles[i].style.top = 10 * (i + 1)
        circles[i].style.bottom = 10 * (i + 1)
        circles[i].style.left = 10 * (i + 1)
        circles[i].style.left = 10 * (i + 1)
      }
    }
  },

  mounted: function() {
    this.circleSizing();
  }

1 个答案:

答案 0 :(得分:2)

您应该使用的方法不是计算属性,而且还循环了一个额外的循环,结果您得到circles[i]是不确定的

Vue.config.devtools = false
Vue.config.productionTip = false

new Vue({
  el: "#app",
  methods: {
    circleSizing() {
      let circles = document.getElementsByClassName("circle")
      for (let i = 0; i <= circles.length - 1 ; i++) {
        circles[i].style.top = 10 * (i + 1) + "px"
        circles[i].style.bottom = 10 * (i + 1) + "px"
        circles[i].style.left = 10 * (i + 1) + "px"
        circles[i].style.left = 10 * (i + 1) + "px"
      }
    }
  },
  mounted() {
      this.circleSizing()
  }
})
.wavyCircles {
  position: relative;
}

.circle {
  position: absolute
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="wavyCircles">
    <div class="circle">u</div>
    <div class="circle">s</div>
    <div class="circle">e</div>
    <div class="circle">m</div>
    <div class="circle">e</div>
    <div class="circle">t</div>
    <div class="circle">h</div>
    <div class="circle">o</div>
    <div class="circle">d</div>
    <div class="circle">i</div>
    <div class="circle">n</div>
    <div class="circle">s</div>
    <div class="circle">t</div>
    <div class="circle">e</div>
    <div class="circle">a</div>
    <div class="circle">d</div>
  </div>
</div>