Как сбросить значения состояния для компонента? - PullRequest
0 голосов
/ 14 июля 2020
• 1000 страница, компонент не уничтожается и данные не обновляются. Есть ли способ сбросить значения состояния vuex для одного и того же компонента .?
const state = {
  page: {},
};
const getters = {
  page(state) {
    return state.page;
  },
};
const mutations = {
  setAPage (state, pPage) {
    state.page = pPage
    state.errors = {}
  },
  setCleanPage(state){
    state.page = null
  },
  reset(state) {
    const s = state();
    Object.keys(s).forEach(key => {
      state[key] = s[key];
    });
    console.log('state', state)
  }
}

const actions = {
  fetchAPage (context, payload) {
    context.commit("setCleanPage");
    const {slug} = payload;
    return ApiService.get(`pages/${slug}/`)
      .then((data) => {
        context.commit("setAPage", data.data);
      })
      .catch((response) => {
        context.commit("setError", response.data)
      })
  },
  resetAPage(context){
    context.commit("reset");
  }
};
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

и в моем компоненте:

<script>
import { mapGetters, mapActions, mapMutations } from "vuex";
export default {
    name: "Page",
    
    computed: {
    ...mapGetters('pages', {page: 'page'}),
  },
  beforeRouteLeave (to, from, next) {
    // called when the route that renders this component has changed,
    // but this component is reused in the new route.
    // For example, for a route with dynamic params /foo/:id, when we
    // navigate between /foo/1 and /foo/2, the same Foo component instance
    // will be reused, and this hook will be called when that happens.
    // has access to >this component instance.
    console.log(to)
    console.log(from)
    console.log(next)

    this.$store.dispatch('pages/resetAPage');
 
  },
  methods: {
    ...mapActions(['pages/fetchAPage']),
  },
  destroyed() {
   this.toggleBodyClass('removeClass', 'landing-page');
   this.$store.dispatch('pages/resetAPage');
  },
  created() {
    this.$store.dispatch('pages/fetchAPage' , this.$route.params) 
  },
};
</script>

Как я могу сбросить или обновить данные для того же компонента?

Спасибо

Ответы [ 2 ]

1 голос
/ 14 июля 2020

Вы можете использовать этот пакет для своих сбросов - https://github.com/ianwalter/vue-component-reset

Вы можете использовать beforeRouteLeave охранник в своем компоненте (ах), если вы хотите поймать навигацию вдали от маршрут, на котором используется компонент (https://router.vuejs.org/guide/advanced/navigation-guards.html#in -component-guards )

Защита компонента beforeRouteUpdate вызывается только тогда, когда компонент использовался в текущем маршруте и для повторного использования в следующем маршруте.

0 голосов
/ 14 июля 2020

Я бы посоветовал вам следить за этим изменением параметров.

Я не знаю, как вы используете свои параметры, но вы можете передать их своему компоненту в качестве свойств, а затем добавить к ним наблюдателя, который вызовет ваше действие сброса vuex.

// in your router
// ... some routes
{
  path: "/page/:id",
  props: true, // this passes :id as prop to your component
  component: Page
}

В вашем компоненте

export default {
  name: "Page",
  props: ["id"],  // your route param
  computed: {
    ...mapGetters('pages', {page: 'page'}),
  },
  beforeRouteLeave (to, from, next) {
    // called when the route that renders this component has changed,
    // but this component is reused in the new route.
    // For example, for a route with dynamic params /foo/:id, when we
    // navigate between /foo/1 and /foo/2, the same Foo component instance
    // will be reused, and this hook will be called when that happens.
    // has access to >this component instance.
    console.log(to)
    console.log(from)
    console.log(next)

    this.$store.dispatch('pages/resetAPage');
 
  },
  methods: {
    ...mapActions(['pages/fetchAPage']),
  },
  watch: {
    id() { // watch the id and reset the page if it has changed or add additionnal logic as needed
      this.$store.dispatch('pages/resetAPage');
    }
  },
  destroyed() {
   this.toggleBodyClass('removeClass', 'landing-page');
   this.$store.dispatch('pages/resetAPage');
  },
  created() {
    this.$store.dispatch('pages/fetchAPage' , this.$route.params) 
  },
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...