source

Vuex에서 작업이 완료되면 저장소에서 구성 요소 함수 호출

factcode 2022. 7. 21. 23:33
반응형

Vuex에서 작업이 완료되면 저장소에서 구성 요소 함수 호출

새 요소가 추가되면 요소 목록이 포함된 div의 맨 아래로 자동으로 스크롤하려고 합니다.

API를 사용하여 Axios를 통해 요소 추가 및 삭제가 이루어지기 때문에 Vuex에서 상태를 업데이트하려면 서버로부터의 응답을 기다려야 합니다.

즉, 일단 요소가 내 상태에 추가되면 "scrollDown" 함수를 호출할 때마다 함수가 두 번째 마지막 요소까지 스크롤됩니다(비동기 Axios 호출이 아직 등록되지 않았기 때문입니다).

궁금한 점은 Vuex에서 작업이 완료될 때까지 기다렸다가 컴포넌트의 함수를 호출하여 div의 맨 아래로 스크롤하려면 어떻게 해야 합니까?

감시자를 동원해서 속성을 계산하고 소품을 보내고 Vuex의 실제 상태에서의 변화를 추적해봤지만 아무 소용이 없었어요

// VUEX

const state = {
  visitors: [],
  url: 'API URL',
  errors: []
}
const mutations = {
  ADD_VISITOR(state, response) {
    const data = response.data;
    data.Photos = [];
    state.visitors.data.push(data);
  },
}
const actions = {
  addVisitor: ({ commit }, insertion) => {
    axios
      .post(state.url + 'api/visitor', {
        name: insertion.visitorName
      })
      .then(response => {
        commit('ADD_VISITOR', response);
      })
      .catch(error => state.errors.push(error.response.data.message));
    state.errors = [];
  },
}

// MY COMPONENT FROM WHERE THE ACTIONS ARE BEING DISPATCHED

<div ref="scroll" class="visitors-scroll">
  <ul v-if="visitors.data && visitors.data.length > 0" class="list-group visitors-panel">
    <!-- Displaying appVisitor component and sending data as a prop -->
    <app-visitor v-for="visitor in visitors.data" :key="visitor.id" :visitor="visitor"></app-visitor>
  </ul>
</div>

methods: {
  // Function that dispatches the "addVisitor" action to add a new visitor to the database
  newVisitor() {
    const insertion = {
      visitorName: this.name
    };
    if (insertion.visitorName.trim() == "") {
      this.errors.push("Enter a valid name!");
    } else {
      this.$store.dispatch("addVisitor", insertion);
      this.name = "";
    }
    this.errors = [];
    this.scrollDown(); // I WANT TO CALL THIS FUNCTION WHEN AXIOS CALL IS FINISHED AND MUTATION IN VUEX IS COMPLETED
  },
  scrollDown() {
    this.$refs.scroll.scrollTop = this.$refs.scroll.scrollHeight;
  }
},

어떤 도움이라도 감사합니다!

vuex에서 디스패치된 액션은 Promise를 반환합니다.코드의 경우 반환할 것이 없기 때문에 빈 Promise입니다.Promise를 반환/통과한 후 컴포넌트에서 기다려야 합니다.이 고정 코드를 보세요.

// VUEX

const state = {
  visitors: [],
  url: 'API URL',
  errors: []
}
const mutations = {
  ADD_VISITOR(state, response) {
    const data = response.data;
    data.Photos = [];
    state.visitors.data.push(data);
  },
}
const actions = {
  addVisitor: ({ commit }, insertion) => {
    return axios
      .post(state.url + 'api/visitor', {
        name: insertion.visitorName
      })
      .then(response => {
        commit('ADD_VISITOR', response);
      })
      .catch(error => state.errors.push(error.response.data.message));
    state.errors = [];
  },
}

// MY COMPONENT FROM WHERE THE ACTIONS ARE BEING DISPATCHED

<div ref="scroll" class="visitors-scroll">
  <ul v-if="visitors.data && visitors.data.length > 0" class="list-group visitors-panel">
    <!-- Displaying appVisitor component and sending data as a prop -->
    <app-visitor v-for="visitor in visitors.data" :key="visitor.id" :visitor="visitor"></app-visitor>
  </ul>
</div>

methods: {
  // Function that dispatches the "addVisitor" action to add a new visitor to the database
  newVisitor() {
    const insertion = {
      visitorName: this.name
    };
    if (insertion.visitorName.trim() == "") {
      this.errors.push("Enter a valid name!");
    } else {
      this.$store.dispatch("addVisitor", insertion)
        .then(() => {
           this.scrollDown();
         })
      this.name = "";
    }
    this.errors = [];
  },
  scrollDown() {
    this.$refs.scroll.scrollTop = this.$refs.scroll.scrollHeight;
  }
},

구문을 사용해 볼 수도 있습니다.

이것은 언제가 될 때까지 기다릴지를 의미합니다.this.$store.dispatch("addVisitor", insertion)해결되었습니다.즉, API로부터의 응답이 있을 때까지 다음 줄의 코드는 실행되지 않습니다.

methods: {
  // Function that dispatches the "addVisitor" action to add a new visitor to the database
  async newVisitor() {
    const insertion = {
      visitorName: this.name
    };
    if (insertion.visitorName.trim() == "") {
      this.errors.push("Enter a valid name!");
    } else {
      await this.$store.dispatch("addVisitor", insertion);
      this.name = "";
    }
    this.errors = [];
    this.scrollDown();
  },
  scrollDown() {
    this.$refs.scroll.scrollTop = this.$refs.scroll.scrollHeight;
  }
}

편집: Vueux 작업에서는 반드시 다음 항목을 추가합니다.return진술.

const actions = {
  addVisitor: ({ commit }, insertion) => {
    return axios
      .post(state.url + 'api/visitor', {
        name: insertion.visitorName
      })
      .then(response => {
        commit('ADD_VISITOR', response);
      })
      .catch(error => state.errors.push(error.response.data.message));
    state.errors = [];
  },
}

언급URL : https://stackoverflow.com/questions/55419184/calling-a-component-function-from-the-store-once-an-action-is-complete-in-vuex

반응형