1

Как передать во функцию fetchPosts ище 1 параметр

  <wiz-slide>
    <p>{{count}}</p>
    <div class = 'posts' v-for="post in allPosts" :key="post.id">
        <h2>{{post.title}}</h2>
        <h2>{{post.email}}</h2>
        <p>{{post.body}}</p>
    </div>
  </wiz-slide>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  props: ['count'],
  data() {
    return {
      type: 'posts',
      id: '',
      posts: [],
    };
  },
  //   computed: {
  //     allPosts() {
  //       return this.$store.getters.allPosts;
  //     },
  //   },
  computed: mapGetters(['allPosts']),
  methods: {
    ...mapActions(['fetchPosts']),
    toggle() {
      console.log(this.count);
      this.fetchPosts(this.count, this.type);
    },
  },
  async mounted() {
    // console.log('22');
    // const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=3');
    // const posts = await res.json();
    // this.posts = posts;
    // this.$store.dispatch('fetchPosts', 2);
    console.log(this.count);
    console.log('i popal');
    console.log(this.type);
  },
  beforeUpdate() {
    this.toggle();
  },
};
</script>
<style scoped></style>
Vuex Сюда передаю
import Vuex from 'vuex';
import actions from './actions';
import mutations from './mutations';

export default () => new Vuex.Store({
  state: {
    posts: [],
  },
  actions: {
    async fetchPosts(ctx, limit = 3, comments) {
      const res = await fetch(`${`https://jsonplaceholder.typicode.com/${comments}?_limit=`}${limit}`);
      const posts = await res.json();

      ctx.commit('updatePosts', posts);
    },
  },
  mutations: {
    updatePosts(state, posts) {
      state.posts = posts;
    },
  },
  getters: {
    allPosts(state) {
      return state.posts;
    },
  },

  modules: {

  },
});

1 ответ 1

0

Ну вообще в экшн передаются 2 параметра. Это, собсно, контекст и нагрузка. Так вот нагрузку лучше передавать одним объектом. Например

async fetchPosts(ctx, { limit: 3, comments: comments, filter: filter }) {
  const res = await fetch(`${`https://jsonplaceholder.typicode.com/${comments}?_limit=`}${limit}`);
  const posts = await res.json();
  ctx.commit('updatePosts', posts);
},

А в компоненте уже вызывать так

methods: {
    ...mapActions(['fetchPosts']),
    toggle() {
      console.log(this.count);
      this.fetchPosts({ limit: this.count, comments: this.type, filter: this.filter });
    },
  },

Это избавит в будущем от проблем, когда надо будет менять сигнатуру, например, на бэкэнде. Когда одним объектом приходит это всё-таки удобнее. Да и вообще, вроде как, именно так и говорят делать в доке. Хотя про это могу ошибаться. Но в доке точно есть 2 параметра у экшена. Это контекст и payload. И вот этот пэлоад надо делать объектом. А в этом объекте уже сколько угодно параметров передавать.

1
  • Спасибо,за объяснения!
    – TUTURU
    23 мар 2020 в 14:25

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.