source

Vuej가 구성 요소에서 참조에 액세스할 수 없음

goodcode 2022. 8. 12. 23:21
반응형

Vuej가 구성 요소에서 참조에 액세스할 수 없음

컴포넌트 템플릿 내에 있는 캔버스 요소를 가져오려고 합니다.vuejs1에 대한 설명서는 훌륭하지만 vuejs2에 대한 설명서는 찾을 수 없습니다.여기서 요소를 가져오려면 "ref"가 유일한 방법입니다.오브젝트는 취득하고 있습니다만, 변수에 액세스 하려고 하면 정의되어 있지 않습니다.

HTML

<div id="app>
  <template id="image-capture">
    <div class="row" >
      <canvas ref="icanvas" ></canvas>
    </div>
  </template>
</div>

JS


const ic = {
  template: '#image-capture' ,
   
  created () {
    console.log(this.$refs); //this returns object
    console.log(this.$refs.icanvas); // but this is undefined
  }
}

const routes = [
  { path: '/ic', component:   ic},
]

const router = new VueRouter({
  routes 
})

 new Vue({
  router,
   }).

$mount('#app')

이칸바스 요소를 가져와야 해

여기에 콘솔 로그는

created템플릿이 처리되기 전에 기동됩니다.
상세한 것에 대하여는, https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram 를 참조해 주세요.

다음 URL에서 $ref에 액세스할 수 있습니다.mounted이벤트

mounted: function() {
    console.log(this.$refs.icanvas);
},

$nextTick() 함수를 사용할 수 있습니다.$nextTick() 내의 코드는 DOM 업데이트 후에 실행됩니다.

this.$nextTick(function () {

    console.log(this.$refs.ANY_COMPONENT_REF)

})

저도 같은 문제가 있었습니다만, 제 경우 nextTick과 v-if를 변경하는 방법으로 ref에 접속하여 해결했습니다.

methods: {
open() {
  this.show = true; //v-if condition
    this.$nextTick(function() {
      this.titleWidth = this.$refs.titleBg.clientWidth - 30;
    });
}

@Dan Levin의 대답은 효과가 있다.

methods: {
fecthData() {
    this.data ={ ... }; // assume the fetched data have changed DOM here.

    this.$nextTick(() => {
      console.log(this.$refs); // returns obj
      console.log(this.$refs.target); // returns el
    });
}

v-for에서도 사용할 수 있습니다.

저도 이 오류가 발생했습니다.이 문제를 수정하는 방법은 업데이트된 후크에서 레퍼런스를 얻는 것입니다.아래 예를 참조하십시오.

데이터 오브젝트에 'products'라는 빈 배열이 있습니다.

data() {
    return {
        products: []
    }
}

업데이트된 후크에서 참조가 있는지 확인합니다.그렇지 않으면 아무 일도 일어나지 않습니다.그런 다음 제품이 발견되면 스크립트가 계속됩니다.다음에 Vue가 갱신된 훅에 다시 접속할 때, 제품 어레이의 길이가 1개보다 길기 때문에 스크립트는 다시 트리거되지 않습니다(물론 참조를 찾을 수 있는 경우).

updated() {
    let products = this.$refs.products;
    if (!products || this.products.length > 0) return;

    this.products = products;
    // run your logic here
}

5월경에는v-for예를 들어 다음과 같습니다.

<li class="list__item" v-for="(item,index) in pubList" :key="index">
   <img
      class="list__img lazy_image"
      ref="lazyImages"
    >
</li>

그리고.

 //pubList is from ajax
 props: ['pubList'],

이 경우 다음 방법으로 해결합니다.

  watch: {
    'pubList': {
        handler:function(newArray) {
             if(newArray.length===0){
                return
              }
             this.$nextTick(function() {
               console.log(this.$refs.lazyImages)
             })
          },
       immediate:true
    }
  }

vue instance에서 self variable을 가리키려면 정보 소스

created() {
    let self = this;
    console.log(self.$refs.icanvas);
},

언급URL : https://stackoverflow.com/questions/40884194/vuejs-cant-access-refs-from-component

반응형