【问题标题】:Update Vue from Class Object property从类对象属性更新 Vue
【发布时间】:2021-08-13 07:08:48
【问题描述】:

我有一个包含属性的自定义类,我想知道如何更新我的 vue 文件以反映属性更改。为了简单起见,我精简了我的自定义类(我将在未来扩展它以拥有更多属性。

在此示例中,我希望 btn 在用户根据我的自定义类秒表上的属性“isPlaying”单击它时更改颜色和图标。

ma​​in.vue

<template>
  <q-page padding class="text-center q-pa-md">
    <q-btn
        :color="sw.isPlaying ? 'red' : 'green'"
        :icon="sw.isPlaying ? 'mdi-pause' : 'mdi-play'"
        @click="sw.toggle()"
    />
  </q-page>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  computed,
  onMounted,
  onUnmounted
} from '@vue/composition-api';
import Stopwatch from 'src/utils/stopwatch';

export default defineComponent({
  name: 'Stopwatch',
  components: {},
  setup() {
    const sw = computed(() => new Stopwatch());
    return {
      sw
    };
  }
});
</script>

stopwatch.ts

export default class Stopwatch {
  isPlaying: boolean;

  constructor() {
    this.isPlaying = false;
  }

  // Start timer or continue from paused time
  startTimer() {
    this.isPlaying = true;
    console.log('play');
  }

  // Stop/Pause the timer
  stopTimer() {
    this.isPlaying = false;
    console.log('stop');
  }

  // Start/Stop timer or continue from paused time
  toggle() {
    if (this.isPlaying) {
      this.stopTimer();
    } else {
      this.startTimer();
    }
  }
}

【问题讨论】:

    标签: typescript vue.js vue-composition-api


    【解决方案1】:

    代替computed,使用reactive 使Stopwatch 实例的道具反应:

    import { defineComponent, reactive } from '@vue/composition/api'
    
    export default defineComponent({
      setup() {
        const sw = reactive(new Stopwatch());
        return {
          sw
        };
      }
    });
    

    demo

    【讨论】:

    • 感谢分享这个演示,而不仅仅是代码。非常感谢
    猜你喜欢
    • 2021-02-08
    • 2023-02-21
    • 2019-03-08
    • 2022-01-02
    • 2013-01-18
    • 1970-01-01
    • 2020-07-16
    • 2012-03-16
    • 2016-07-13
    相关资源
    最近更新 更多