IT이야기

Vuejs 3 - data() 및 setup() 이외의 후크에서 템플릿으로 데이터를 전송하는 방법

cyworld 2022. 6. 1. 17:38
반응형

Vuejs 3 - data() 및 setup() 이외의 후크에서 템플릿으로 데이터를 전송하는 방법

저는 Vue/VueX에 익숙하지 않기 때문에 잘 모르는 부분이 있을 것입니다.

매우 간단한 컴포넌트가 있습니다.

  • VueX에서 항목 컬렉션을 가져옵니다.mapState(인computed())
  • (in)에서 단일 아이템을 가져옵니다.mounted()현시점에서는)
  • 그런 다음 해당 항목을 템플릿에 푸시해야 하는데 알 수 없습니다.

제가 알기로는 데이터를 템플릿에 푸시할 수 있는 것은setup또는data메서드.mounted,created훅 등이게 맞나?

다음 코드 예에서는 어떻게 하면item내가 얻는 물건itemsmounted()템플릿에 추가하시겠습니까?

로는 할 수 없다setup나의 이래computed()VueXitems오브젝트를 아직 사용할 수 없습니다.이 간단한 목표를 올바르게 달성하는 방법에 대해 제안해 주실 수 있습니까?

<template>
  <p>ID: {{ id }}</p>
  <p>Name:: {{ item.name }}</p>
</template>

<script lang="ts">
import { useRoute } from 'vue-router'
import { ref, computed, watch } from 'vue'
import { mapState, mapActions } from 'vuex'

export default {
  // fetching items from vuex (works)
  computed: mapState({
    items: (state: any) => state.items
  }),
  setup() {
    const route = useRoute()
    // parsing ID from route params (works)
    const id = ref(route.params.id || 'Plants')
    return {
      id,
      // this seems to be the proper way of pushing data to template:
      // item: { name: 'this works from here' }
    }
  },
  mounted() {
    // fetch item by id (works)
    const item: Plant = this.items.find(i => i.id === this.id)

    // TODO: I need to push this to the template but I cannot from here
    return { item }
  }
}
</script>

이 경우 다음과 같은 다른 계산 속성을 정의하는 가장 좋은 방법은 다음과 같습니다.

export default {
 
  computed:{ ...mapState({//should spread the mapState in order to add other properties
    items: (state: any) => state.items
  }),
  item(){
    const _item: Plant = this.items.find(i => i.id === this.id)
    return  _item;
   }

 },
  setup() {
    const route = useRoute()
    // parsing ID from route params (works)
    const id = ref(route.params.id || 'Plants')
    return {
      id,
     
    }
  },

}

또는 options api만을 사용합니다.

export default {
 
  computed:{ ...mapState({//should spread the mapState in order to add other properties
    items: (state: any) => state.items
  }),
  item(){
    let id=this.$route.params.id || 'Plants'
    const _item: Plant = this.items.find(i => i.id === id)
    return  _item;
   }

 },

}

그리고.

<template>
  <p>ID: {{ $route.params.id }}</p>
  <p>Name:: {{ item.name }}</p>
</template>

언급URL : https://stackoverflow.com/questions/64975508/vuejs-3-how-to-send-data-to-template-from-other-hooks-than-data-and-setup

반응형