问题描述
我正在创建一个表单,其中数据来自外部 api 并存储在 Vuex 中。我在官方 Vuex Documentation
中实现了双向计算属性<template>
<form>
<div v-if="email">
<label for="email">E-Mail</label>
<input v-model="email" type="email" id="email">
</div>
</form>
</template>
<script>
export default {
computed: {
email: {
get() {
return this.$store.state.shop.customer.customer.email;
},set(value) {
this.$store.commit('shop/customer/updateEmail',value);
}
},}
}
</script>
当我通过路由访问组件时,一切正常。但是如果我重新加载页面,就会出现错误:
undefined is not an object (evaluating 'this.$store.state.shop.customer.customer.email')
从我读过的其他线程来看,问题是,计算属性重新加载时为空。但是在实施 v-if
指令后,我仍然收到此错误。我想我需要找到一种方法,该属性不为空,就像回退一样,它返回一个空字符串。
VueX 商店:
export const state = () => ({
customer: {},})
export const getters = {
customer: state => state.customer,}
export const mutations = {
updateEmail(state,email) {
state.customer.email = email;
},}
解决方法
您应该使用空字符串初始化状态中的 email
属性,以便在初始加载时进行定义:
export const state = () => ({
customer: { email : ""},})