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 に答える