programing

VueJS 서버 사이드 렌더링: 계산된 속성이 스토어의 변경을 볼 수 없습니다.

bestcode 2022. 8. 25. 23:54
반응형

VueJS 서버 사이드 렌더링: 계산된 속성이 스토어의 변경을 볼 수 없습니다.

서버측 렌더링을 VueJs로 실행하려고 합니다.

저는 공식 문서를 따르고 있습니다. 그리고 저는 이 예를 악리를 사용해서 작동시키려 하고 있습니다.가 에 됩니다.mutation.

https://ssr.vuejs.org/guide/data.html

이 페이지도 찾아서 getters, vuex mapState, mapGetter 등의 예를 대부분 사용해 보았습니다.

vue.view 2 vuex에서 스토어 값을 감시하는 방법

있습니다.store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import { fetchPage } from './api'

export function createStore () {
    return new Vuex.Store({
        strict: true,

        state: () => ({
            res: {}
        }),

        actions: {
            actXY ({ commit }, page) {
                fetchPage('homepage').then((item) => {
                    commit('mutXY', { page, item });
                }).catch(error => {
                    throw new Error(`Store ${error}`);

                })
            }
        },

        mutations: {
            mutXY (state, { page, item }) {
                Vue.set(state.res, page, item);
                console.log(state.res.homepage.data)

            }
        },

        getters: {
            getXY (state) {
                return state.res
            }
        }
    })
}

콘솔 로그에 올바른 정보가 표시되므로 Axios 엔드포인트가 작동하고 상태 개체를 업데이트하고 있음을 의미합니다.'아까', '아까', '아까', ''라고 부르려고 .mutationgetter되지 않았습니다.getter따라서 컴포넌트에 새로운 것은 표시되지 않습니다.

은 것은입니다.HomePage.vue:

<template>
  <div v-if="htmlData">{{ JSON.stringify(htmlData) }}</div>
  <div v-else>loading?</div>
</template>

<script>
export default ({
    name: 'homepage',

    computed: {
        htmlData () {
            console.log("computed = " + JSON.stringify(this.$store.state.res));
            console.log(this.$store.getters.getXY);
            return this.$store.getters
            // return this.getQuery()
        }
    },

    serverPrefetch () {
        return this.getData()
    },

    mounted () {
        console.log("in mounted")
        if (!this.item) {
            this.getData()
        }
    },

    methods: {
        getData () {
            return this.$store.dispatch('actXY', 'homepage')
        }
    }
})

</script>

된 바와 같이, 있는 as as as 。htmlData뭇매를 맞다

{"getXY":{}}

네, 저는 스토어 아이템을 반품하는 방법에 대해 다른 많은 변형을 시도했습니다.getter,아무것도 안 먹혀요.

링크에 것 설정 만, 「」를 추가하려고 .async"/", getData()

또한 컴포넌트에서 직접 악시오 호출을 시도했지만 성공하지 못했습니다.

이것은 SSR로 변환하는 VueJS에서 이미 어느 정도 완료된 프로젝트이기 때문에 패키지에서 모든 것을 삭제했습니다.이전 vue 패키지 중 하나가 경합을 일으킬 수 있다는 생각에 모든 패키지를 다시 설치했습니다.

공식 문서에서 스토어 코드 분할을 시도하고, 루트가 어떻게 쓰여지는지에 대한 변형도 시도했습니다.전혀 효과가 없어요.

현재 코드를 실행할 때 인쇄문에 표시된 내용을 추가해야 합니다.

computed = undefined
computed mm  = undefined
getter = {}
computed get  = {"getXY":{}}
{
  title: 'Home'...}

변환이 설정되기 전에 컴포넌트의 계산된 속성이 실행됩니다.이로 인해 변환이 갱신되기 전에 getter가 호출됩니다.마찬가지로, 에 변경을 호출하려고 합니다.res저장소가 호출되고 렌더링될 때 돌연변이에는 아무것도 없습니다.

실행하려는 코드 레포입니다.https://github.com/dt1/vue-ssr-attempt

(정답을 알아냈다.레포는 현재 기능하고 있는 것으로 갱신하고 있습니다.제 솔루션에 대한 설명은 다음과 같습니다.)

첫번째storeData()=>storeData(state)

그리고나서return this.$store.state.items.homepage.data=>return this.$store.state.items.homepage && return this.$store.state.items.homepage.data(또는 빈 홈페이지에서 상태 항목을 초기화합니다.)

Vue.js에는 SSR가 없습니다.이 예에서는 클라이언트의 데이터를 얻을 수 있습니다.

Store에 대해 다음 예를 사용해 보십시오.

export default new Vuex.Store({
  strict: true,
  state: {
    res: null
  },
  getters: {
    getXY(state) {
      return state.res;
    }
  },
  mutations: {
    mutXY(state, payload) {
      state.res = payload;
    }
  },
  actions: {
    actXY: function(store) {
      fetchPage("homepage")
        .then(res => {
          store.commit("mutXY", res);
        })
        .catch(error => {
          throw new Error(`Store ${error}`);
        });
    }
  }
});

또한 다음과 같이 구성 요소에 데이터를 가져올 수 있습니다.

  computed: {
    htmlData() {
      return this.$store.getters.getXY;
    }
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      return this.$store.dispatch("actXY", "homepage");
    }
  }

제 질문은 왜 이 모든 것이this.getData()기마로 불려왔나?

프로세스를 올바르게 이해한 경우 서버 측 렌더링을 호출하면 vue 컴포넌트가 마운트되기 전에 HTML을 렌더링하려고 합니다.전화해도 될까요?this.getData()탑재된 것이 아니라 생성되었습니까?

다른 시도도 해보겠습니다.

  1. hardcode html 컴포넌트 내의 데이터 값을 사용하여 렌더링 여부를 확인합니다.
  2. 이것이 작동한다면 저장소의 htmlData 값을 하드코드하여 컴포넌트가 해당 저장소의 데이터를 가져와 올바르게 렌더링할 수 있는지 확인합니다.
  3. 그 후 컴포넌트에서 디스패치를 통해 서버에서htmlData를 가져와 동작하는지 확인합니다.
  4. (3)이 동작하지 않는 경우 htmlData를 이미 htmlData가 준비되어 있는 경우에만 생성되는 하위 컴포넌트에 푸시하여 소품을 통해 htmlData를 하위 컴포넌트에 htmlData를 전송합니다.

알았어, 드디어 알아냈어

내가 마주친 주요 문제는 고장난 전화였다.내가 주문을 수정했을 때, 나는 그 주문에 대해Converting circular structure to JSON에러입니다.다음으로 VueJ, Vuex 스토어 및 Axios 간의 콜백 기능을 이해하려고 했습니다.

제가 생각해낸 최종 해결책은 다음과 같습니다.

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import * as util from 'util'

Vue.use(Vuex)

import { fetchPage } from './api'

export function createStore () {
    return new Vuex.Store({
        strict: true,

        state: () => ({
            res: {}
        }),

        actions: {
            actXY ({ commit }, page) {
                return fetchPage(page).then(item => {
                    commit('mutXY', { page , item } );
                })
            }
        },

        mutations: {
            mutXY (state, {page, item }) {
                Vue.set(state.res, page, item);
            }
        }
    })
}

그리고 나서 공리당에게 전화를 걸 때, 나는 반드시 그 전화만 돌려줘야 했다.response.data전체 응답 대신.그 전에, 저는 그 전에...unhandled promise에러입니다.

api.js

import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios);

Vue.axios.defaults.baseURL = '<url goes here>';

export function fetchPage(page){
    return Vue.axios.get(page).then((resp => resp.data))
}

마지막으로 중요한 것은Homepage.vue.

업데이트를 실행하려면 getData()를 비동기화해야 합니다.

<template>
<div v-if="htmlData">
  <div>{{ htmlData.title }}</div>
  <div>{{ htmlData.description }}</div>
  <div>{{ htmlData.html }}</div>
</div>
</template>

<script>
export default ({
    name: 'homepage',
    computed: {
        htmlData () {
            return this.$store.state.res.homepage
        }
    },

    serverPrefetch () {
        return this.getData()
    },
    mounted () {
        if (!this.item) {
            this.getData()
        }
    },
    methods: {
        async getData () {
            await this.$store.dispatch('actXY', 'homepage')
        }
    }
})
</script>

이 모든 문제를 겪고 있는 모든 사람에게 도움이 되길 바랍니다.

언급URL : https://stackoverflow.com/questions/61835978/vuejs-sever-side-rendering-computed-property-not-seeing-changes-in-store

반응형