如何将帖子从一个组件转移到另一个组件?

时间:2019-05-14 16:05:08

标签: vue.js vue-component vuex vue-router

下午好,请告诉我。我现在正在使用Vuex进行培训,并且无法将帖子从一个组件转移到另一个组件。我有一个组件分页,所有帖子和历史记录组件都存储在其中,并且应该将我单击以访问它们的前5个帖子发送给他们。也就是说,它应大致作为查看帖子的历史记录。我在这里写了一些代码,但没有显示我的帖子,告诉我我做错了什么以及如何解决它。

存储所有帖子的组件代码:

    <template>
  <div class = "app">
    <ul>
      <li v-for="(post, index) in paginatedData" class="post" :key="index">
        <router-link :to="{ name: 'detail', params: {id: post.id, title: post.title, body: post.body} }" @click="addPostToHistoryComp(post.id, post.title, post.body)">
        <img src="src/assets/nature.jpg">
        <p class="boldText"> {{ post.title }}</p>
        </router-link>
        <p> {{ post.body }}</p>
      </li>
      </ul>
        <div class="allpagination">
          <button type="button" @click="page -=1" v-if="page > 0" class="prev"><<</button>
          <div class="pagin">
            <button class="item"
            v-for="n in evenPosts"
            :key="n.id"
            v-bind:class="{'selected': current === n.id}"
            @click="page=n-1">{{ n }} </button>
          </div>
          <button type="button" @click="page +=1" class="next" v-if="page < evenPosts-1">>></button>
        </div>
      </div>
    </template>

    <script>
      import {mapState} from 'vuex'
      export default {
        name: 'app',
        data () {
          return {
            current: null,
            page: 0,
            visiblePostID: '',
          }
        },
        mounted(){
          this.$store.dispatch('loadPosts')
        },
        computed: {
          posts(){
            return this.$store.state.posts
          },
          search(){
            return this.$store.state.sSearch
          },
          evenPosts: function(posts){
            return Math.ceil(this.posts.length/6);
          },
          paginatedData() {
            const start = this.page * 6;
            const end = start + 6;
            return this.filteredPosts.slice(start, end);
          },
          filteredPosts() {
            return this.posts.filter((post) => {
              return post.title.match(this.search);
            });
          },
        },
        methods: {
          addPostToHistoryComp(val){
            this.$store.dispatch('transforPostToHistoryComp', { // как вызвать actions с объект с параметром
              pTitle: val.post.title,
              pBody: val.post.body,
              pId: val.post.id
            })
          },
        }
      }
    </script>

应显示最近打开的5条帖子的“历史记录”组件的代码:

    <template>
  <div class="history">
    <ul>
      <li v-for="(historyPost, index) in historyPosts" class="post" :key="index">        
        <img src="src/assets/nature.jpg">
        <p class="boldText"> {{ post.title }}</p>
        <p> {{ post.body }}</p>
      </li>
      </ul>
  </div>
</template>

<script>
  export default{
    computed: {
      historyPosts(){
        return this.$store.state.historyPosts
      },
    },

  }
</script>

还有我的故事代码(Vuex):

    export default new vuex.Store({
  state: {
    posts: [],
    sSearch: '',
    title: '',
    body: '',
    id: Number,
    historyPosts: []
  },
  actions: {
    loadPosts ({commit}) {
      axios.get('http://jsonplaceholder.typicode.com/posts').then(response => {
        let posts = response.data
        commit('SET_POSTS', posts)
      }).catch(error => {
        console.log(error);
      })
    },
    transforTitleAndBody({commit}, payload){ // мутация которая изменяет сосотаяние в sSearch
      const todo = {
        title: payload.sTitle,
        body: payload.sBody,
        id: payload.sId
      }
      axios.post('http://jsonplaceholder.typicode.com/posts', todo).then(_ => {
        commit('ADD_TODO', todo)
      }).catch(function (error) {
          console.log(error);
        })
    },
    transforPostToHistoryComp({commit}, payload){ // мутация которая изменяет сосотаяние в sSearch
      const todohistory = {
        title: payload.pTitle,
        body: payload.pBody,
        id: payload.pId
      }
      commit('ADD_TODO_HISTORY', todohistory)
    }
  },
  mutations: {
    SET_POSTS(state, posts) {
      state.posts = posts
    },
    transforSearch(state, payload){ // мутация которая изменяет сосотаяние в sSearch
      state.sSearch = payload
    },
    ADD_TODO (state, todoObject) {
      state.posts.unshift(todoObject)
    },
    ADD_TODO_HISTORY (state, todohistoryObject) {
      state.historyPosts.unshift(todohistoryObject)
    },
  },
})

1 个答案:

答案 0 :(得分:1)

我发现了发生了什么。您对文件Pagination.vue的代码有一些误解

您将@click放在<router-link>下,这是行不通的,因为路由器链接更改了页面,从而在离开前阻止了其他事件。

我对模板和脚本进行了一些更改。我认为可以。

    <template>
  <div class="app">
    <ul>
      <template v-for="(post, index) in paginatedData">
        <li class="post" :key="index" @click="addPostToHistoryComp(post)">
          <img src="src/assets/nature.jpg">
          <p class="boldText">{{ post.title }}</p>
          <p>{{ post.body }}</p>
        </li>
      </template>
    </ul>
    <div class="allpagination">
      <button type="button" @click="page -=1" v-if="page > 0" class="prev"><<</button>
      <div class="pagin">
        <button
          class="item"
          v-for="n in evenPosts"
          :key="n.id"
          v-bind:class="{'selected': current === n.id}"
          @click="page=n-1"
        >{{ n }}</button>
      </div>
      <button type="button" @click="page +=1" class="next" v-if="page < evenPosts-1">>></button>
    </div>
  </div>
</template>

    <script>
import { mapState } from "vuex";
export default {
  name: "app",
  data() {
    return {
      current: null,
      page: 0,
      visiblePostID: ""
    };
  },
  mounted() {
    this.$store.dispatch("loadPosts");
  },
  computed: {
    posts() {
      return this.$store.state.posts;
    },
    search() {
      return this.$store.state.sSearch;
    },
    evenPosts: function(posts) {
      return Math.ceil(this.posts.length / 6);
    },
    paginatedData() {
      const start = this.page * 6;
      const end = start + 6;
      return this.filteredPosts.slice(start, end);
    },
    filteredPosts() {
      return this.posts.filter(post => {
        return post.title.match(this.search);
      });
    }
  },
  methods: {
    addPostToHistoryComp(post) {
      this.$store.dispatch("transforPostToHistoryComp", {
        pTitle: post.title,
        pBody: post.body,
        pId: post.id
      });

      this.$router.push({
        name: "detail",
        params: { id: post.id, title: post.title, body: post.body }
      });
    }
  }
};
</script>