【问题标题】:Vue.js State value reset from the input after hard refresh. How to fix it?Vue.js 硬刷新后从输入中重置状态值。如何解决?
【发布时间】:2021-12-27 06:36:35
【问题描述】:

我是 Vue.js 的新手,我创建了一个编辑个人资料页面,用户可以在其中编辑基本信息,例如:

  • 名字
  • 姓氏
  • 电子邮件

输入示例:

<b-col sm="6">
    <b-form-group
        label="First Name"
        label-for="firstName"
    >
        <validation-provider
        #default="{ errors }"
        name="First Name"
        rules="required"
        >
        <b-form-input
            id="firstName"
            v-model="firstName"
            placeholder="First Name"
            name="firstName"
        />
        <small class="text-danger">{{ errors[0] }}</small>
        </validation-provider>
    </b-form-group>
</b-col>

现在我正在从状态值中加载用户值,如下所示:

data() {
    return {
        firstName: '',
        lastName: '',
        email: '',
        required,
    }
},
mounted() {
    this.firstName = this.$store.state.authUser.user.firstName
    this.lastName = this.$store.state.authUser.user.lastName
    this.email = this.$store.state.authUser.user.email
},

它运行良好并在输入中显示出价值。 但是当用户点击硬刷新时,所有输入的值都会消失。

知道如何解决这个问题吗?由于我是 Vue.js 的新手并且正在从事第一个项目,因此我找不到任何方法。

谢谢

【问题讨论】:

  • 您可能会添加一个onbeforeunload JavaScript 事件处理程序,将表单值存储在本地存储中,然后您可以在页面加载时检查本地存储以查看是否需要在页面加载。

标签: javascript vue.js


【解决方案1】:

存储只在内存中,所以如果页面被刷新,所有数据都消失了。

有多种方法可以将数据保存在浏览器中并保留,即使在刷新后也是如此。我建议查看以下内容: https://github.com/robinvdvleuten/vuex-persistedstate

我还发现您的问题已在此处得到解答: Vuex state on page refresh

还建议使用这样的持久状态: 从'vuex'导入{商店} 从'vuex-persistedstate'导入createPersistedState 从 'js-cookie' 导入 * 作为 Cookies

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      getState: (key) => Cookies.getJSON(key),
      setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true })
    })
  ]
})

此外,由于您是初学者,这里有一个技巧可以让您的代码更加整洁。 像这样导入 mapState:

import { mapState } from 'vuex';

并像这样使用您的商店变量:

  computed: {
    ...mapState({
      firstName: state => state.authUser.user.firstName,
      lastName: state => state.authUser.user.lastName ,
      email: state => state.authUser.user.email ,
    }),
  },

那么你就可以像往常一样使用这些了。

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 2019-09-11
    • 2020-12-31
    • 2021-03-23
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多