【问题标题】:Vue JS - Rendering getter before templateVue JS - 在模板之前渲染 getter
【发布时间】:2021-06-01 18:14:25
【问题描述】:

我收到 TypeError "Cannot read property 'email' of undefined",因为模板似乎在 getter 返回值之前呈现。该值确实是未定义的,因为它在商店中被初始化为未定义。但是在模板渲染之后,该值确实返回了一些东西。无论如何我可以在模板之后渲染我的 getter 吗?

我的代码:

<template>
  <div>
    <Success :title="'title name'"
             :subtitle="`your email is ${schoolDetails.email}.`"
             :button-text="'button text'"
             :button-link="ROUTE_NAMES_HK_ADMIN.SCHOOL_DETAILS"/>
  </div>
</template>

<script>
import {ROUTE_NAMES_HK_ADMIN} from "@/router/modules/hkAdmin";
import Success from "@/components/partials/Success";
import {GET_SCHOOL_BY_ID} from "@/store/manager/actions";

export default {
  name: "SchoolCreateSuccess",
  components: {Success},
  data: () => ({
    ROUTE_NAMES_HK_ADMIN
  }),
  computed: {
    schoolDetails: function () {
      return this.$store.getters.getSelectedSchool;
    },
  },
  methods: {
    getSchoolDetails: function (schoolId) {
      this.$store.dispatch(GET_SCHOOL_BY_ID, schoolId);
    }
  },
  created() {
    this.getSchoolDetails(this.$route.params.id);
  }
}

【问题讨论】:

    标签: javascript vue.js vuex getter


    【解决方案1】:

    如何用虚拟值初始化 schoolDetails 变量来解决错误? 那么也许您可以使用 watch 而不是计算来将跟踪 schoolDetails 变量与存储的数据对齐。

    所以,也许是这样的:

    data: () => ({
      ROUTE_NAMES_HK_ADMIN,
      schoolDetails: {email: ''}
    }),
    // note: 'watch' track changes (no changes == the function will not be called)
    watch: {
      // watch the state, not the getter
      '$store.state.selectedSchool': () => {
        this.schoolDetails = this.$store.getters.getSelectedSchool;
        return;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-08
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 2018-07-05
      • 2019-01-03
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      相关资源
      最近更新 更多