首页 > 解决方案 > 验证 | V-alert :值只是在更新属性时显示不关闭

问题描述

我有一个 v-alert 组件将基于 Vuex 商店显示/关闭 - 它会设置错误 - 并在 4 秒后清除它!

这是我的 V-alert 组件:

问题是它在成为:value时不起作用getErrornull

如果我希望我的 V-alert 在getErroris时消失null,我必须使用v-if

:value我的解决方法没问题,但我仍然在这里感到困惑

是否有错误或我在某个地方错了?

<template>
  <v-alert
    :value ="!!getError" // <~~~ Problem here

    transition="scroll-x-transition"

    :type="getError.type"
    :dismissible="$vuetify.breakpoint.mdAndUp"
    dense
    :prominent="$vuetify.breakpoint.mdAndUp"
    class="TrnAlert rounded-tr-xl rounded-bl-xl text-center text-caption text-md-body-1"
    @input="[CLEAR_ERROR]"
  >
    {{ getError.message }}
  </v-alert>
</template>

<script>
  import { mapGetters, mapActions } from 'vuex';

  import { CLEAR_ERROR } from '../../store/type/actions';

  export default {

    computed: {
      ...mapGetters(['getError']),
    },

    methods: {
      ...mapActions([CLEAR_ERROR]),
    },
  };
</script>

<style scoped></style>


这是我的商店 - 它会设置错误 - 并在 4 秒后清除它

import { UPDATE_ERROR, REMOVE_ERROR } from '../type/mutations';
import { SET_ERROR, CLEAR_ERROR } from '../type/actions';

const state = () => ({
  error: null,
});

const getters = {
  getError: (state) => state.error,
};

const actions = {
  [SET_ERROR]({ commit }, payload) {
    commit(UPDATE_ERROR, payload);
    setTimeout(() => {
      commit(REMOVE_ERROR);
    }, 4000);

  },
  [CLEAR_ERROR]({ commit }) {
    commit(REMOVE_ERROR);
  },
};

const mutations = {
  [UPDATE_ERROR]: (state, payload) => {
    state.error = { message: payload.message, type: payload.type || 'error' };
  },
  [REMOVE_ERROR]: (state) => {
    state.error = null;
  },
};

export default {
  state,
  actions,
  mutations,
  getters,
};

标签: javascriptvue.jsvuetify.js

解决方案


非常感谢 @User28 提供他/她宝贵的工作代码段,它帮助我比较并弄清楚我的愚蠢代码发生了什么,

事实证明,当错误在商店中被删除时,它使 state.error = null;

然后犯错误,因为:type="getError.type"getError.message

[Vue 警告]:渲染错误:“TypeError:无法读取属性‘type’ of null”

[Vue 警告]:渲染错误:“TypeError:无法读取未定义的属性‘消息’”

我可以像这样更改商店来修复错误:


const state = () => ({
  error: {
    message: undefined,
    type: undefined,
  },
});

// ...


const mutations = {
// ...

  [REMOVE_ERROR]: (state) => {
    state.error = {
      message: undefined,
      type: undefined,
    };
  },
};

...


推荐阅读