vuex如何存储数据、获取数据、以及数据的持久化

2023-12-13 05:34:14

前提必须已经在vue中安装了vuex插件不然无法使用,不知道怎么创建vue和安装vuex的可以看这个视频,node.js版本最好16以上不然可能会安装失败:30分钟学会Vue之VueRouter&Vuex 趁着暑假掌握一门技能 大学生前端实习毕业设计必备技能_哔哩哔哩_bilibili

1、存储数据:(源码会放在最后)

第一步,在vuex中matations模块中加入存储数据的方法

第二步,在需要提交数据的页面使用this.$store.dispatch方法

通过点击事件submitForm即可将数据传入vuex中。点击跳转到About页面

2、获取数据

在点击跳转的另外一个页面使用this.$store.state.xxx即可获取vuex中数据状态

运行效果:

3、持久化

当我们页面刷新的时候vuex会丢失之前获取的数据,如果想刷新后一直保存数据,我们可以安装插件vuex-persistedstate,

安装指令:

npm install vuex-persistedstate

提醒:必须使用管理员身份运行cmd终端不然可能会因为权限不够导致安装失败

安装成功后按这个模版来书写:

按照这个模版就可以存储state模块中的所有数据了。

运行效果:

源码:

登录页面:

<template>
  <div class="home">
    <div class="samsung">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="账号" prop="pass">
          <el-input  v-model="ruleForm.user" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="ruleForm.age"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"  v-loading.fullscreen.lock="fullscreenLoading">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- <HelloWorld></HelloWorld> -->
  </div>
</template>

<script>
export default {
  data () {
    const checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (value < 18) {
            callback(new Error('必须年满18岁'))
          } else {
            callback()
          }
        }
      }, 1000)
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      fullscreenLoading: false,
      ruleForm: {
        pass: '',
        checkPass: '',
        age: '',
        user: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        age: [
          { validator: checkAge, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!')
          const loading = this.$loading({
            lock: true,
            text: '登录中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          setTimeout(() => {
            const user = this.ruleForm.user
            const pass = this.ruleForm.pass
            const age = this.ruleForm.age
            this.$store.dispatch('setUser', user)
            this.$store.dispatch('setPass', pass)
            this.$store.dispatch('setAge', age)
            loading.close()
            console.log('登录成功')
            this.$router.push('/about')
          }, 2000)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
  .home {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .samsung {
    width: 500px;
    height: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .denglu{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 267px;
    height: auto;
  }
</style>

获取数据的页面:

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <h1>{{user}}</h1>
    <h1>{{pass}}</h1>
    <h1>{{age}}</h1>
  </div>
</template>
<script>
export default {
  data () {
    return {
      user: '',
      pass: '',
      age: 0
    }
  },
  created () {
    this.type()
  },
  methods: {
    type () {
      this.user = this.$store.state.user
      this.pass = this.$store.state.pass
      this.age = this.$store.state.age
      console.log('1', this.user)
      console.log('2', this.pass)
      console.log('3', this.age)
    }
  }
}
</script>

vuex:

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: '',
    pass: '',
    age: 0
  },
  getters: {
  },
  mutations: {
    SET_PASS (state, pass) {
      state.pass = pass
    },
    SET_USER (state, user) {
      state.user = user
    },
    SET_AGE (state, age) {
      state.age = age
    }
  },
  actions: {
    setUser ({ commit }, user) {
      commit('SET_USER', user)
    },
    setPass ({ commit }, pass) {
      commit('SET_PASS', pass)
    },
    setAge ({ commit }, age) {
      commit('SET_AGE', age)
    }
  },
  modules: {
  },
  plugins: [
    createPersistedState({
      // 存储方式:localStorage、sessionStorage、cookies
      storage: window.sessionStorage,
      // 存储的 key 的key值
      key: 'store',
      reducer (state) { // render错误修改
        // 要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据
        return { ...state }
      }
    })
  ]

})

文章来源:https://blog.csdn.net/m0_65069237/article/details/134879795
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。