首页 > 解决方案 > 无法使用道具将对象传递给新路由

问题描述

我正在开展一个项目,用户填写测验并且需要将结果传递到新页面。测验具有测验组件和测验完成组件,用户可以在其中进入结果页面。我已经能够将测验答案传递给 QuizFinished,但问题在于将 QuizFinished 的答案传递给 QuizResults。我已经从这里复制了一些代码,这些代码来自这个stackoverflow 问题,但是代码不起作用。我在这里错过了什么吗?任何帮助将非常感激。

测验.vue

<template>
  <div class="quiz-background py-5" id="mood-finder">
    <b-container class="text-center">
      <h1 class="">Mood finder</h1>
      <component
 <!-- This event is triggered when a question is answered in Question.vue, that works -->
        v-on:click="_answerQuestion($event)"
<!-- Going from the startpage to the quiz -->
        v-on:start="this.startQuiz"
        v-bind:is="component"
<!-- Binds the answers to be read in QuizResult -->
        :answers="answers"
        ref="question"
      />
      <b-row class="d-flex justify-content-center">
        <b-col cols="12" md="8" class="pt-3">
<!-- A progress bar -->
          <b-progress
            variant="primary"
            aria-label="Voortgang van de Moodfinder"
            :value="progress"
            :max="maxProgress"
          ></b-progress>
        </b-col>
      </b-row>
    </b-container>
  </div>
</template>
<script>
import quizStart from "./QuizStart.vue";
import question from "./Question";
import strawberry from "../assets/strawberry.webp";
import banana from "../assets/banana.webp";
import quizFinished from "./QuizFinished.vue";
export default {
  name: "app",
  components: {
    quizStart,
    question,
    quizFinished,
  },
  data() {
    return {
      questionIndex: 0,
<!--The array with the answers. It is put in an object to circumvent the array limitation by Vue: https://github.com/vuejs/vue/issues/1798 -->
      answers: {array: []},
      component: "quizStart",
      strawberry: strawberry,
      banana: banana,
      progress: 0,
      maxProgress: 99,
    };
  },
  methods: {
    /**
     * @description
     * saved pressed answer text in answers array
     */
    _answerQuestion(chosenItem) {
      this.answers.array.push(chosenItem);
      this.switchQuestion();
    },
    startQuiz(){
      this.component= "question"
    },
    /**
     * @description switches the questions when the user performs an action in the quiz
     * it swaps out the quiz images, text and quiz question for each question.
     */
    switchQuestion() {
      /**
       * questionIndex stands for the question the user would like to go to.
       * So e.g questionIndex = 1 is going to the second question (counting from 0)
       */
      this.questionIndex++;
      switch (this.questionIndex) {
        case 0:
          this.progress = 0;
        break;
        // //For question 1, see Question.Vue data field
        case 1:
          this.$refs.question.setQuestion("Question 2");
          this.$refs.question.setItems(
            { name: "strawberry", variety: "sweet" },
            { name: "strawberry", variety: "sweet" },
            { name: "strawberry", variety: "sweet" },
            { name: "strawberry", variety: "sweet" }
          );
          this.$refs.question.setImage(
            this.strawberry,
            this.strawberry,
            this.strawberry,
            this.strawberry
          );
          this.progress = 33;
          break;
        case 2:
          console.log(this.questionIndex)
          this.$refs.question.setQuestion("Question 3");
          this.$refs.question.setItems(
            { name: "banana", variety: "sweet" },
            { name: "banana", variety: "sweet" },
            { name: "banana", variety: "sweet" },
            { name: "banana", variety: "sweet" }
          );
          this.$refs.question.setImage(
            this.banana,
            this.banana,
            this.banana,
            this.banana
          );
          this.progress = 66;
          break;
        case 3:
          this.progress = 99;
       //Goes to the quizFinished component
          this.component = quizFinished;
      }
    },
  },
};
</script>

//removed the styles

QuizFinished.vue:

<template>
  <b-row class="d-flex justify-content-center py-3">
    <b-col class="col-6 col-lg-2">
      <p class="text-white">
        De Mood finder is gemaakt. Je resultaten staan klaar!
      </p>
      <!-- <router-link :to="{ path: '/results/', params: { answers: answers } }"
        ><button class="btn btn-primary" type="button">
          Verder naar resultaten
        </button></router-link
      > -->
      <br />
      <router-link :to="{ name: 'results', params: { params: answers} }"
        >Go to results</router-link>
<!-- For testing purposes, the answers are shown here as: { "array": [{object1} etc.]} -->
      {{ answers }}
    </b-col>
  </b-row>
</template>
<script>
export default {
  name: "quizFinished",
  props: {
//For reasoning behind type: Object, see previous codeblock
    answers: { type: Object, required: false },
  },
};
</script>

//removed styles


测验结果.vue


<!-- Html here -->

<script>
export default {
   props: {
    params: { type: Object, required: false },
  },
  mounted() {
//returns undefined, adding a html object like this: {{params}} returns nothing
    console.log(this.params);
  }
};
</script>

//removed styles

主.js:


import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import './registerServiceWorker';
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue';
import 'bootstrap-vue/dist/bootstrap-vue.css';
import '../src/scss/bootstrap.css';
// Import for fontAwesome : svg-core, brand icons and vue
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { fab } from '@fortawesome/free-brands-svg-icons';
import VueMeta from 'vue-meta';

library.add(fab);
// fontawesome component neccesary to call
Vue.component('font-awesome-icon', FontAwesomeIcon, fab);
// Make BootstrapVue available throughout your project
Vue.component('font-awesome-icon', FontAwesomeIcon, fab);
Vue.use(BootstrapVue);
Vue.use(IconsPlugin);
Vue.use(VueRouter);
Vue.use(VueMeta);

import results from './components/pages/Results';
import index from './components/pages/Index';
import pageNotFound from './components/pages/PageNotFound';
import webshop from './components/pages/Webshop';

const resultsRoute = { path: '/results', name: 'results', component: results, props: true, };
const indexRoute = { path: '/', name: 'index', component: index };
const pageNotFoundRoute = { path: '*', name: 'pageNotFound', component: pageNotFound };
const webshopRoute = { path: '/webshop', name: 'webshop', component: webshop };

const routes = [resultsRoute, indexRoute, pageNotFoundRoute, webshopRoute];

const router = new VueRouter({
    routes,
    mode: 'history',
});

Vue.config.productionTip = false;

new Vue({
    router,
    render: function(h) {
        return h(App);
    },
}).$mount('#app');

标签: vuejs2

解决方案


我最终做的是像这样直接推送到路由器:

在按钮中:

v-on:click="toResults()"
   

在方法中:

         toResults() {
          this.$router.push({
            name: "resultsRoute",
            params: {
              items: this.answers,
            }

然后我能够像这样在另一边获得物品:

vm.$route.params.items

推荐阅读