vue笔记——后台数据存储

1:sessionStorage

localStorage 和 sessionStorage 属性允许在浏览器中存储 key/value 对的数据。

sessionStorage 用于临时保存同一窗口(或标签页)的数据,在关闭窗口或标签页之后将会删除这些数据。

范例:存储数据(表单中提交的数据)
sessionStorage['username'] = this.loginForm.loginName;    
取出数据
sessionStorage['username']

完整代码
 

2:使用vueX

 /*alert('登陆成功');*/
 this.$store.commit('handleUserName', res.data.userName)  /*存至vuex  主页展示用户*/
-------------------------------------------------------------
store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const actions = {}
const mutations = {
handleUserName: (state, user_name) => {
state.userName = user_name
// 把登录的用户的名保存到localStorage中,防止页面刷新,导致vuex重新启动,用户名就成为初始值(初始值为空)的情况
localStorage.setItem('user_name', user_name)
}
}
const state = {
userName: '' || localStorage.getItem('user_name')
}
// getters 只会依赖 state 中的成员去更新
const getters = {
userName: (state) => state.userName
}

const store = new Vuex.Store({
actions,
mutations,
state,
getters
})
export default store;

------------------------------------------------
main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'; /*使用axios*/
import store from './store/store.js'

Vue.use(ElementUI)
Vue.config.productionTip = false
Vue.prototype.axios= axios
axios.defaults.baseURL ='/api/'; //配置请求地址


/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store: store,
components: { App },
template: ''
})
----------------------------------------------
取出数据
{{$store.getters.userName}}
 

 

你可能感兴趣的:(vue笔记——后台数据存储)