Pre:安装
npm install vuex -S
1.首先我们创建一个store文件夹,然后我们在文件夹中放一个store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
login:"isNoLogin"
},
mutations:{
loginchange:(state,qcLogin)=> {
//应对界面刷新,数据会刷新为最原本的login,所以我们在这里进行一下存储
state.login = qcLogin
window.localStorage.setItem('qcLogin', state.login);
},
}
})
2.然后在main .js 中导入
import Vue from 'vue'
import App from './App'
import store from './store/store'
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
})
3.在组件中使用(这里用的是element-ui,有兴趣的话可以了解一下)
template
<el-col :span="3" align="center">
<div class="grid-content bg-purple-light">
<el-button icon="el-icon-view" @click="vuexClick">{{vuex}}</el-button>
</div>
</el-col>
<script>
import { mapState } from 'vuex'
export default {
name: 'App’,
data(){
return{
//创建一个localData,用来接收存储的数据
localData:'',
}
},
created(){
//如果已经存了,就会存储下来,我们在这里直接接收一下
this.localData = window.localStorage.getItem('qcLogin')
console.log(this.localData)
},
/*
computed是在HTML DOM加载后马上执行的,如赋值;
*/
computed: {
//将store.login映射了this.login
...mapState([
'login'
]),
vuex(){
//如果之前commit过mutation,直接使用变化之后的值,如果没有就是用store.login
return this.localData.length >0 ? this.localData:this.login
}
},
methods:{
//测试vuex
vuexClick(){
this.$store.commit("loginchange",'isLogin')
//重新输出
console.log(this.localData)
},
}
</script>