【问题标题】:Object level variables when using TypeScript and Vuejs together?一起使用 TypeScript 和 Vuejs 时的对象级变量?
【发布时间】:2018-06-11 03:12:02
【问题描述】:

我不确定最好的方法是什么。我非常想制作一个组件,并且我有一些我想使用的对象级变量。请看下面的例子:

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,这样我就可以跨方法引用它。我不想将这些变量存储在数据中,因为它们不需要被 vuejs 监控。有没有类似的

this.$privateVariables["paperScope"] = paperScope

那个可以用吗?

我现在唯一的想法是我需要创建一个扩展 vue 的类型定义,并包含类似 $privateVariables 的东西。只是想知道是否有内置或更好的方法来完成我想要完成的工作?

【问题讨论】:

    标签: javascript typescript vue.js vuejs2


    【解决方案1】:

    我不想将这些变量存储在数据中,因为它们不需要被 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;
        }
      }
    })
    

    【讨论】:

    • 这并不能解决使用 Vue 和 TypeScript 的问题。使用 JS 时,根级属性存储在 $options 中,但使用 TypeScript 时,它们存储在数据中,使它们成为反应式。在使用 TS 时如何确保属性以 $options 结尾并不明显。
    猜你喜欢
    • 2020-05-31
    • 2019-04-11
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2012-10-08
    • 2014-08-20
    相关资源
    最近更新 更多