programing

Vuex 스토어에서 사용할 수 있는 값이 반응하지 않음

prostudy 2022. 6. 6. 10:34
반응형

Vuex 스토어에서 사용할 수 있는 값이 반응하지 않음

그래서 API에서 데이터를 가져오고 있습니다.vue-resource상태가 갱신되고 콘솔에서 원하는 값을 확인할 수 있습니다.문제는 저장소에서 데이터를 로드할 때 응용 프로그램이 로드 중인 응용 프로그램에 영향을 주지 않는 것처럼 보이지만, 예를 들어 페이지 간에 바꾸면 정보가 올바르게 표시되는 것입니다.이로 인해 라이프 사이클 훅이 잘못되었거나 vuex 내에서 상태를 잘못 처리했다고 믿게 되었습니다.

Vuex 스토어

import Vue from 'vue'
import Vuex from 'vuex'
import VueResource from 'vue-resource'

Vue.use(VueResource)
Vue.use(Vuex)

const state = {
  twitter: 0,
  instagram: 0,
  youtube: 0,
  twitch: 0
}

const actions = {
  LOAD_METRICS: ({commit}) => {
    Vue.http.get('http://109.74.195.166:2000/metrics').then(response => {
      let out = [{
        twitter: Number(response.body[0].twitter),
        instagram: Number(response.body[0].instagram),
        youtube: Number(response.body[0].youtube),
        twitch: Number(response.body[0].twitch)
      }]
      commit('SET_METRICS', out)
    }).catch((e) => {
      console.log(e)
    })
  }
}

const mutations = {
  SET_METRICS (state, obj) {
    state.twitter = obj[0].twitter
    state.instagram = obj[0].instagram
    state.youtube = obj[0].youtube
    state.twitch = obj[0].twitch
  }
}

const getters = {}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})

여기서 저는 돌연변이를 이용해 필요한 정보를 수집하는 이벤트를 디스패치하려고 합니다.

<template>
  <div id="app">
    <NavigationTop></NavigationTop>
    <router-view></router-view>
    <SocialBar></SocialBar>
    <CopyrightBar></CopyrightBar>
  </div>
</template>

<script>

  export default {
    name: 'app',
    ready: function () {
      this.$store.dispatch('LOAD_METRICS')
    }
  }
</script>

<style>
  @import url('https://fonts.googleapis.com/css?family=Roboto:400,700,900');

  #app {
    font-family: 'Roboto', sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: white;
    background: url('./assets/Images/bodyBackground.jpg');
  }
</style>

마지막으로 countup.js에서 사용할 컴포넌트 내 정보를 요청하고 데이터 내 메서드에도 전달합니다.

<template>
  <div class="hero">
    <div class="container hero-content">
      <div class="row hero-back align-items-end">
        <div class="col-lg-6">
          <div class="row">
            <div class="col-lg-6" v-for="icons in socialIcons">
              <Hero-Tile
                :name="icons.name"
                :icon="icons.iconName"
                :count="icons.count"
                :numeric="icons.numeric"
              ></Hero-Tile>
              <h1>{{origin}}</h1>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="diagonal-left-lines"></div>
    <div class="home-hero-img"><img class="img-fluid" src="../../assets/Images/home-hero.jpg"></div>
  </div>
</template>

<script>
  import HeroTile from './Hero-Tile'
  import CountUp from 'countup.js'

  export default {
    components: {HeroTile},
    name: 'hero',
    data () {
      return {
        origin: '',
        socialIcons: [
          {
            name: 'twitter',
            iconName: 'twitter',
            count: this.$store.state.twitter,
            numeric: 26000
          },
          {
            name: 'instagram',
            iconName: 'instagram',
            count: this.$store.state.instagram,
            numeric: 35000
          },
          {
            name: 'youtube',
            iconName: 'youtube-play',
            count: this.$store.state.youtube,
            numeric: 15000
          },
          {
            name: 'twitch',
            iconName: 'twitch',
            count: this.$store.state.twitch,
            numeric: 127000
          }
        ]
      }
    },
    methods: {
      updateNumbers: function () {
        let options = {
          useEasing: true,
          useGrouping: true,
          separator: ',',
          decimal: '.',
          prefix: '',
          suffix: 'K'
        }

        function kFormatter (num) {
          return num > 999 ? (num / 1000).toFixed(1) : num
        }

        let twitter = new CountUp('twitter', 0, kFormatter(this.$store.state.twitter), 0, 3, options)
        let instagram = new CountUp('instagram', 0, kFormatter(this.$store.state.instagram), 0, 3, options)
        let youtube = new CountUp('youtube', 0, kFormatter(this.$store.state.youtube), 0, 3, options)
        let twitch = new CountUp('twitch', 0, kFormatter(this.$store.state.twitch), 0, 3, options)
        twitter.start()
        instagram.start()
        youtube.start()
        twitch.start()
      }
    },
    mounted: function () {
      this.updateNumbers()
    }
  }
</script>

현시점에서는 「0k」를 로드하는 것 같기 때문에, 실제로 로드업시에 정보를 로드하지 않는 레이스 상태가 발생하고 있는 것 같습니다.하지만 여기서 올바른 접근법이 무엇인지 잘 모르겠습니다.

이 문제는 결국 해킹으로 해결되었습니다. 현시점에서는 정확한 정답을 알 수 없기 때문입니다.내가 가진 게 먹히긴 하지만.

관심 사항:

가게

LOAD_METRICS: ({commit}, context) => {
    console.log(context)
    if (context === true) {
      return new Promise((resolve) => {
        resolve('loaded')
      })
    }
    return new Promise((resolve) => {
      Vue.http.get('real ip is normally here').then(response => {
        let out = {
          twitter: Number(response.body[0].twitter),
          instagram: Number(response.body[0].instagram),
          youtube: Number(response.body[0].youtube),
          twitch: Number(response.body[0].twitch),
          loaded: false
        }
        commit('SET_METRICS', out)
        resolve(out)
      }).catch((e) => {
        console.log(e)
      })
    })
  }

상기에서 나는 현재 전류의 인스턴스를 보내고 있다.store.state.metrics.loaded에 액세스 합니다.그런 다음 현재 값의 진실성을 확인하기 위해 체크합니다.첫 번째 로드는 항상 false를 반환해야 하므로 API 호출을 사용하여 약속을 반환하고 스토어를 변환하여 나중에 값을 얻습니다.따라서 로딩된 이벤트를 true로 변환했기 때문에 다음 이후의 인스턴스는 true 값을 반환하고 새로운 약속이 해결되어 확실하게 할 수 있습니다..then()핸들러가 존재합니다.

요소

created: function () {
      this.$store.dispatch('LOAD_METRICS', this.$store.state.metrics.loaded).then((res) => {
        if (res !== 'loaded') {
          this.updateNumbers(res)
        } else {
          this.socialIcons[0].count = this.kFormatter(this.$store.state.metrics.twitter) + 'K'
          this.socialIcons[1].count = this.kFormatter(this.$store.state.metrics.instagram) + 'K'
          this.socialIcons[2].count = this.kFormatter(this.$store.state.metrics.youtube) + 'K'
          this.socialIcons[3].count = this.kFormatter(this.$store.state.metrics.twitch) + 'K'
        }
      })
    }

델의 컴포넌트 내created라이프 사이클 후크 결과 값을 사용하여 DOM 내에서 컴포넌트가 다시 생성될 때 취할 경로를 식별합니다.이번에는 값을 로드하고 일반 데이터 바인딩으로 DOM을 업데이트할 수 있습니다.

나는 행동 설정자 내에서 국가의 논리를 숙고하고 약속을 반환하는 것보다 더 나은 접근 방법이 있다고 믿는다..then()들이이있있있있

언급URL : https://stackoverflow.com/questions/44478123/values-not-reactive-once-available-in-vuex-store

반응형