0

我需要将值传递给数据中的样式属性,但是,由于 vuejs 和 JS 范围的工作方式,它不会让我通过 this.data.property 访问:

Vue.component ('loader-component', {
  template: '#loader-template',

  mounted: function() {
    this.animationTest();
  },

  data: function() {
    return {
      svg: true,
      timer: 0,
      // styles
      position: {
        marginLeft: '',
        marginTop: '',
        float: 'left'
      }
    };
  },

  methods: {
    animation: function() {
      let timer = 0,
          itemWidth = 60,
          domWidth = document.getElementById('awesome-body').clientWidth,
          domHeight = document.getElementById('awesome-body').clientHeight,
          marginL = -2 * itemWidth,
          marginT = Math.floor((Math.random() * domHeight) + 1);
          this.position.marginTop = marginT;
      setInterval(function() {
        marginL = marginL + timer * 5;
        timer++;
        // console.log(marginL);
        this.position.marginLeft = marginL;
      }, 1000); // time interval in milliseconds
    }
  } // methods finishes

});

这将触发下一个错误:

Cannot set property 'marginLeft' of undefined.

直接从 setInterval 函数到 data.marginTop 的语法是什么?

谢谢!

4

2 回答 2

1

this是引用 setInterval 函数而不是组件。做这个:

methods: {
    animation: function() {
      let component = this,
          timer = 0,
          itemWidth = 60,
          domWidth = document.getElementById('awesome-body').clientWidth,
          domHeight = document.getElementById('awesome-body').clientHeight,
          marginL = -2 * itemWidth,
          marginT = Math.floor((Math.random() * domHeight) + 1);

      component.position.marginTop = marginT;

      setInterval(function() {
        marginL = marginL + timer * 5;
        timer++;
        // console.log(marginL);
        component.position.marginLeft = marginL;
      }, 1000); // time interval in milliseconds
    }
}
于 2016-10-31T19:56:02.550 回答
0

我认为你应该尝试另一种方法。问题是您指的是尚未呈现的元素。

有几种方法可以完成您想做的事情。

1/样式绑定

使用这种方法,您将能够将数据绑定到样式,并且当您的数据更新时,它会自动更新您的模板。

<template>
  <div :style="{ 'margin-left': whateverFunction() }">
  </div>
</template>

<script>
  ...
  methods: {
    whateverFunction () {
      return this.some_attribute + 'px'
    }
  }
  ...
</script>

除了函数,这也可以是计算属性或属性。

2/过渡内置系统

您似乎想在元素上实现过渡,所以实现这一目标的简单方法是使用内置系统。如果您想在转换过程中拥有更多控制权,可以使用javascript 挂钩来帮助您在转换期间操作数据。

3/ 使用布尔值和ref

如果您真的想访问代码中的 DOM 元素,您应该使用布尔值等待模板完全呈现,在此处输入链接描述并使用ref特殊属性轻松获取所需元素。

如果您需要对部分代码的特定帮助,请给我们一个 jsfiddle 来测试和调试它。

于 2016-11-01T10:23:57.157 回答