前提必须已经在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.userconst pass = this.ruleForm.passconst age = this.ruleForm.agethis.$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.userthis.pass = this.$store.state.passthis.age = this.$store.state.ageconsole.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、cookiesstorage: window.sessionStorage,// 存储的 key 的key值key: 'store',reducer (state) { // render错误修改// 要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据return { ...state }}})]})