search

Home  >  Q&A  >  body text

How to use vue class components

<script lang="ts">
import { defineComponent, ref, nextTick, unref, onMounted } from 'vue';

import { useScript } from '/@/hooks/web/useScript';

const BAI_DU_MAP_URL = 'https://api.map.baidu.com/getscript?v=3.0&ak=xxx';
export default defineComponent({
  setup() {
    const wrapRef = ref<HTMLDivElement | null>(null);
    const { toPromise } = useScript({ src: BAI_DU_MAP_URL });

    async function initMap() {
      await toPromise();
      await nextTick();
      const wrapEl = unref(wrapRef);
      if (!wrapEl) return;
      const BMap = (window as any).BMap;
      const map = new BMap.Map(wrapEl);
      const point = new BMap.Point(116.404, 39.915);
      map.centerAndZoom(point, 15);
      map.enableScrollWheelZoom(true);
    }

    onMounted(() => {
      initMap();
    });

    return { wrapRef };
  },
})
</script>

vue class component

<script lang="ts">
import { ref, nextTick, unref } from 'vue'
import {Vue} from 'vue-property-decorator'
import { useScript } from '/@/hooks/web/useScript'

const BAI_DU_MAP_URL = 'https://api.map.baidu.com/getscript?v=3.0&ak=xxx';

export default class LogisticsDetail extends Vue {
  private wrapRef = ref<HTMLDivElement | null>(null)
  private toPromise = useScript({ src: BAI_DU_MAP_URL })

  async initMap() {
    await this.toPromise();
    await nextTick();
    const wrapEl = unref(this.wrapRef);
    if (!wrapEl) return;
    const BMap = (window as any).BMap;
    const map = new BMap.Map(wrapEl);
    const point = new BMap.Point(116.404, 39.915);
    map.centerAndZoom(point, 15);
    map.enableScrollWheelZoom(true);
  }

  mounted() {
    this.initMap()
  }

}
</script>

const { toPromise } = useScript({ src: BAI_DU_MAP_URL }); -->private toPromise = useScript({ src: BAI_DU_MAP_URL })

mistake:

Uncaught (in promise) TypeError: this.toPromise is not a function

How to write and use vue-class-component?

P粉529245050P粉529245050276 days ago408

reply all(1)I'll reply

  • P粉864872812

    P粉8648728122024-02-27 00:10:46

    Since vue-class-component is deprecated in Vue 3, an alternative is available: vue-faceing-decorator.

    reply
    0
  • Cancelreply