Vue 读取 null 属性时 watcher 的回调错误

Error in callback for watcher in Vue reading properties of null

保存 data/s 后我的控制台出现此错误。我不熟悉 Vue 中的手表。虽然它读取值但是在 v-model="selected 上它捕获来自手表 属性.

的回调错误

Error in callback for watcher "selected": "TypeError: Cannot read properties of null(reading 'value')"

我的组件代码:

<template>
  <v-select
    :items="project_types"
    item-text="description"
    item-value="id"
    v-model="selected"
    return-object
    :menu-props="{ bottom: true, offsetY: true }"
    append-icon="fas fa-chevron-down"
    placeholder="Type"
    outlined
    dense
  />
</template>

<script>
import {
  httpSuccessResponseLogger,
  httpErrorResponseLogger
} from "@/helpers/logger";

export default {
  name: "TypeDropdown",
  data: () => ({
    project_types: [],
    selected: null
  }),
  methods: {
    getProjectStatuses() {
      this.$api.get("providers/project-types")
        .then(response => {
          httpSuccessResponseLogger(response);

          this.project_types = this.$_.get(response, "data.result.project_types", []);

        })
        .catch(error => {
          httpErrorResponseLogger(error);
        })

    }
  },
  created() {
    this.getProjectStatuses();
  },
  watch: {
    selected(item) {
      console.log({valueOf: item.value})
      this.$store.commit("projects/SET_FILTER_TYPE", {
        type: item.value
      });
    }
  }
};
</script>

<style scoped></style>

在我的 Vuex 中使用模块:

export default {
  namespaced: true,
  state: {
    filter: {
      type: []
    }
  },
  getters: {},
  mutations: {
    SET_FILTER_TYPE: (state, { type }) => (state.filter.type = type)
  },
  actions: {

  }
};

希望能帮到你。问题是 this.$refs.form.reset(); 以及如何使我的数据等于非空值或空值。当我删除 this.$refs.form.reset(); 时,它工作正常,但表格中有数据。

由于某些原因,item有时会被设置为null,如果您想从null读取任何属性(例如值),它将显示类型错误。

?代表可选(ES2020),当你试图从nullundefined获取属性时,它不会再通过添加[来显示错误=13=].

查看更多关于 ?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

所以:

item.value

改为:

item?.value