搜尋

首頁  >  問答  >  主體

Vue 3 Composition API - 潛在的空對象

我使用 Vue 3 Composition apiTypescript 來使用 HammerJS 套件實現捏合縮放。

我正在嘗試遵循 CodePen 用 Ja​​vaScript 編寫的工作範例:https://codepen.io/bakho/details/GBzvbB 在 Vue 中實作。

但是,當我嘗試使其在我的 Vue 應用程式中運行時遇到了一些問題,我不確定如何解決它。

以下錯誤:

#
// Object is possibly 'null'.
imageContainer.value.offsetWidth;

// Object is possibly 'null'.
imageContainer.value.appendChild(displayImage);

// Object is possibly 'null'.
imageContainer.value.addEventList ener...

這是完整的原始碼:

<template>
  <h1>Image Zoom</h1>
  <div class="imageContainer" ref="imageContainer"></div>
</template>

<script lang="ts">
import Hammer from "hammerjs";
import { defineComponent } from "vue";
import { ref } from 'vue';

export default defineComponent({
  setup() {
    const imageUrl = "https://source.unsplash.com/random";
    const imageContainer = ref(null)

    let minScale = 1; let maxScale = 4; let imageWidth : any; let imageHeight : any; let containerWidth : any;
    let containerHeight : any; let displayImageX = 0; let displayImageY = 0; let displayImageScale = 1;
    let displayDefaultWidth : any; let displayDefaultHeight 
    let rangeX = 0; let rangeMaxX = 0; let rangeMinX = 0;
    let rangeY = 0; let rangeMaxY = 0; let rangeMinY = 0;

    // let displayImageRangeY = 0;

    let displayImageCurrentX = 0;
    let displayImageCurrentY = 0;
    let displayImageCurrentScale = 1;

    function resizeContainer() {
      containerWidth = imageContainer.value.offsetWidth;
      containerHeight = imageContainer.value.offsetHeight;
      if (displayDefaultWidth !== undefined && displayDefaultHeight !== undefined) {
        displayDefaultWidth = displayImage.offsetWidth;
        displayDefaultHeight = displayImage.offsetHeight;
        updateRange();
        displayImageCurrentX = clamp(displayImageX, rangeMinX, rangeMaxX);
        displayImageCurrentY = clamp(displayImageY, rangeMinY, rangeMaxY);
        updateDisplayImage(
          displayImageCurrentX,
          displayImageCurrentY,
          displayImageCurrentScale
        );
      }
    }
    resizeContainer();

    function clamp(value, min, max) {
      return Math.min(Math.max(min, value), max);
    }

    function clampScale(newScale) {
      return clamp(newScale, minScale, maxScale);
    }

    const displayImage = new Image();
        displayImage.src = imageUrl;
        displayImage.onload = function(){
        imageWidth = displayImage.width;
        imageHeight = displayImage.height;
        imageContainer.value.appendChild(displayImage);
        displayImage.addEventListe ner('mousedown', e => e.preventDefault(), false);
        displayDefaultWidth = displayImage.offsetWidth;
        displayDefaultHeight = displayImage.offsetHeight;
        rangeX = Math.max(0, displayDefaultWidth - containerWidth);
        rangeY = Math.max(0, displayDefaultHeight - containerHeight);
    }

    imageContainer.value.addEventLis tener('wheel', e => {
        displayImageScale = displayImageCurrentScale = clampScale(displayImageScale + (e.wheelDelta / 800));
        updateRange();
        displayImageCurrentX = clamp(displayImageCurrentX, rangeMinX, rangeMaxX)
        displayImageCurrentY = clamp(displayImageCurrentY, rangeMinY, rangeMaxY)
        updateDisplayImage(displayImageCurrentX, displayImageCurrentY, displayImageScale);  
    }, false);

    function updateDisplayImage(x, y, scale) {
        const transform = 'translateX(' + x + 'px) translateY(' + y + 'px) translateZ(0px) scale(' + scale + ',' + scale + ')';
        displayImage.style.transform = transform;
        displayImage.style.webkitTransform = transform;
        displayImage.style.transform = transform;
    }

    function updateRange() {
        rangeX = Math.max(0, Math.round(displayDefaultWidth * displayImageCurrentScale) - containerWidth);
        rangeY = Math.max(0, Math.round(displayDefaultHeight * displayImageCurrentScale) - containerHeight);
        
        rangeMaxX = Math.round(rangeX / 2);
        rangeMinX = 0 - rangeMaxX;

        rangeMaxY = Math.round(rangeY / 2);
        rangeMinY = 0 - rangeMaxY;
    }

    const hammertime = new Hammer(imageContainer);
    hammertime.get('pinch').set({ enable: true });
    hammertime.get('pan').set({ direction: Hammer.DIRECTION_ALL });

    hammertime.on('pan', ev => {  
        displayImageCurrentX = clamp(displayImageX + ev.deltaX, rangeMinX, rangeMaxX);
        displayImageCurrentY = clamp(displayImageY + ev.deltaY, rangeMinY, rangeMaxY);
        updateDisplayImage(displayImageCurrentX, displayImageCurrentY, displayImageScale);
    });

    hammertime.on('pinch pinchmove', ev => {
        displayImageCurrentScale = clampScale(ev.scale * displayImageScale);
        updateRange();
        displayImageCurrentX = clamp(displayImageX + ev.deltaX, rangeMinX, rangeMaxX);
        displayImageCurrentY = clamp(displayImageY + ev.deltaY, rangeMinY, rangeMaxY);
        updateDisplayImage(displayImageCurrentX, displayImageCurrentY, displayImageCurrentScale);
    });

    hammertime.on('panend pancancel pinchend pinchcancel', () => {
        displayImageScale = displayImageCurrentScale;
        displayImageX = displayImageCurrentX;
        displayImageY = displayImageCurrentY;
    }); 

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

<style>
.imageContainer {
  width: 96%;
  height: 96%;
  max-width: 800px;
  max-height: 600px;
  position: absolute;
  overflow: hidden;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  background: #2b2b2c;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.imageContainer > img {
  display: block;
  max-width: 100%;
  max-height: 100%;
  cursor: move;
  touch-action: none;
}
</style>

任何人都可以告訴我出了什麼問題以及為什麼會導致此 Object 可能為“null”

P粉821808309P粉821808309411 天前697

全部回覆(1)我來回復

  • P粉752826008

    P粉7528260082023-11-09 00:11:04

    這就是該錯誤的原因:

    • const imageContainer = ref(null) -> 您將值設為null 並且TypeScript 警告您對該物件的屬性的任何存取都可能引發錯誤,因為初始值為null 並且因為您嘗試在模板中使用ref 該元素可以存在,也可以不必存在。

    • const imageContainer = document.querySelector('.imageContainer') -> 您正在查詢存在或不存在的HTML 元素,這表示您也可以取得null 作為值,並且TypeScript 再次警告您對該物件的屬性的任何存取都可能引發錯誤

    解決方案:

    • 您必須實際從setup 函數傳回setup 變量,以便Vue 將其與模板中的ref 綁定,並且可以在onMounted 函數內部存取該變量,因為它是ref ,這意味著它尚未安裝到DOM 中。 setup 在 Vue.js 元件生命週期中的 createdmounted 掛鉤之前調用,並且您無權存取其中的任何 DOM 內容。
    import { ref, onMounted } from 'vue'
    
    export default {
      setup() {
        const imageContainer = ref(null)
    
        onMounted(() => {
          // here you access imageContainer variable
        })
    
        return {
          imageContainer 
        }
      }
    }
    

    回覆
    0
  • 取消回覆