前提必須已經在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 }}})]})