2017-12-31 335 views
2

私はこのための最良のアプローチが何であるか分かりません。私はコンポーネントを作りたいと思っていますが、私は利用したいオブジェクトレベルの変数をいくつか持っています。以下の例を参照してください。TypeScriptとVuejsを併用する場合のオブジェクトレベル変数

import Vue from "vue" 
import * as paper from "paper" 

export default Vue.extend({ 

    template: ` 
     <div class="chart-container" ref="chart-container"> 
      <canvas ref="canvas"></canvas> 
     </div> 
    `, 

    mounted: function() { 

     this.$nextTick(function() { 
      let canvas = this.$refs["canvas"] as HTMLCanvasElement 
      let chartContainer = this.$refs["chart-container"] as HTMLDivElement 
      // Obviously errors out as there is no definition for the variable paperScope 
      this.paperScope = new paper.PaperScope() 
      this.paperScope.setup(canvas) 
     }) 
    }, 

    methods: { 
     resizeCanvas(): void { 
      let chartContainer = this.$refs["chart-container"] as HTMLDivElement 
      let width = chartContainer.clientWidth - 30; 
      let height = chartContainer.clientHeight - 30; 
      // Want to access the class level variable in declared methods 
      this.paperScope.view.viewSize = new paper.Size(width, height) 
     } 
    } 
}) 

私はオブジェクトレベルの変数paperScopeを持っていますので、メソッド間で参照できるようにしたいと思います。私はvuejによって監視される必要がないので、これらの変数をデータに格納したくない。何かありますか?

this.$privateVariables["paperScope"] = paperScope 

などありますか?

今私の考えは、vue 1を拡張し、$ privateVariablesのようなものを含む型定義を作成する必要があるということだけです。私が成し遂げようとしていることを組み込む、あるいはより良い方法があるかどうか疑問に思うだけですか?

答えて

0

これらの変数は、vuejsで監視する必要がないため、データに格納する必要はありません。

このような非反応性変数を実現したい場合は、$optionsを使用してそれらを保存することができます。私はthis issue commentからこのテクニックも学びました。

https://jsfiddle.net/ujd1h586/

HTML:

<div id="app"> 
    <p>{{ message }}</p> 
    <button @click="updateText"> 
    update 
    </button> 
</div> 

Vueのコンポーネント:

new Vue({ 
    el: '#app', 

    privateVariable: 'Thanks Vue.js!', 

    data() { 
    return { 
     message: 'Hello Vue.js!' 
    }; 
    }, 

    methods: { 
    updateText() { 
     this.message = this.$options.privateVariable; 
    } 
    } 
}) 
関連する問題