programing

Vuex getter 반환 정의되지 않은 값

sourcetip 2022. 8. 8. 22:58
반응형

Vuex getter 반환 정의되지 않은 값

스토어를 가지고 있고, getter에 콜을 하고 있습니다만, 정의되어 있지 않습니다.스토어에서 store param 값을 인쇄하려고 했는데 정의되어 있지 않습니다.페이지 리프레쉬가 되면 정상적으로 동작합니다.

이것은 store.js, getter는 courseBy라고 불립니다.아이디

export const store = new Vuex.Store({
  state: {
    title: "CBCode",
    courseCategories: [
      {
        title: "Fundamentos de Programación",
        categoryName: "fundamentos",
        description:
          "Eres nuevo en la programación? Estas en el lugar indicado, aqui contarás con todo lo necesario para empezar",
        links: ["PSeInt", "C++"],
        color: "is-success"
      },
    ],
    courses: [
      {
        id: 1,
        name: "PSeInt",
        category: "fundamentos"
      },
      {
        id: 2,
        name: "C++",
        category: "fundamentos"
      },
      {
        id: 3,
        name: "C#",
        category: "poo"
      },
    ],
    dailyUpdates: [
      "@usuario ha terminado un curso",
      "Tienes nuevos mensajes en la bandeja",
      "Hay un nuevo usuario",
      "Hay esto bla",
      "lorem ipsum dolor quien sabe que"
    ]
  },
  getters: {
    categoryColor: state => categoryName => {
      return state.courseCategories.filter(
        category => category.categoryName == categoryName
      )[0];
    },
    courses: state => {
      // https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
      let array = state.courses;

      let currentIndex = array.length,
        temporaryValue,
        randomIndex;

      // While there remain elements to shuffle...
      while (0 !== currentIndex) {
        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
      }

      return array;
    },
    coursesPaginated: state => {
      let arrays = [],
        size = 3;
      while (state.courses.length > 0)
        arrays.push(state.courses.splice(0, size));

      return arrays;
    },
    courseById: state => id => {

      console.log(state)

      return state.courses.find(course => parseInt(course.id) === parseInt(id));
    }
  },

main.discloss.main.discloss.

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import { store } from "./store/store";
import toastr from "toastr";
import "./registerServiceWorker";

import "./sass/styles.scss";

Vue.config.productionTip = false;

toastr.options = {
  positionClass: "toast-top-right"
};

Vue.prototype.$toastr = toastr;

new Vue({
  store,
  router,
  render: h => h(App)
}).$mount("#app");

이것은 내 컴포넌트입니다.

<template>
  <div>
    <form>
      <div class="form-control">
        <label class="label has-text-white">Nombre:</label>
        <input type="text" class="input" v-model="course.name">
      </div>
      <hr>
      <button class="button is-primary" @click="updateCourse">Actualizar</button>
    </form>
  </div>
</template>

<script>
import {mapGetters} from "vuex";

export default {
  name: "DashboardEditCourse",
  data: () => ({
    course: {
      id: 0,
      title: "",
      name: ""
    }
  }),
  methods: {
    updateCourse() {
      this.$store.commit("UPDATE_COURSE", this.course);
    }
  },
  computed: {
    ...mapGetters(['courseById'])
  },
  mounted() {
    console.log(this.courseById(this.$route.params.id));
    this.course = this.courseById(this.$route.params.id);
  }
};
</script>

다른 라이프 사이클 훅을 사용했지만 아무것도 사용하지 않았습니다.getter에서는 find 대신 filter를 사용했지만 아무것도 사용하지 않았습니다.

다음을 사용하여 플러그인 초기화Vue.use

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const store = new Vuex.Store({

이런 식으로 매장을 수출하면 안 됩니다.여기 더 좋은 방법이 있다

store.displaces를 설정합니다.

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store = new Vuex.Store({
  // your code
});

export default store;

main.discloss.main.discloss.

import store from "./store";

new Vue({
  store,
  render: h => h(App)
}).$mount("#app");

언급URL : https://stackoverflow.com/questions/55072661/vuex-getter-return-undefined-value

반응형