在vue脚手架运用vuex(状态管理器)+ 登录后用户名的保存

版权声明:非经本人同意,请勿转载。 https://blog.csdn.net/QQ_Empire/article/details/82016555

1、安装vuex,

           命令:npm i vuex -D

2、在src文件里新建一个store文件夹,然后 创建store.js文件,

        在store.js里引入vue   ,vuex  如下

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)

import state from './state'

var mutations={
	login(a,b){
		a.count+=b
	},
	jian(a){
		a.count--
	}
}

export default new Vuex.Store({
	
	state,
	mutations
	
})

3、如果state数据比较多,可给state单独建个文件,state.js,然后暴露一下

var state={
	count:0
}

export default state

      在store.js接收一下

store.js文件

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)

import state from './state'

var mutations={
	login(a,b){
		a.count++
	},
	jian(a){
		a.count--
	}
}

export default new Vuex.Store({
	
	state,
	mutations
	
})

4、在main.js文件里引入import store from './store/store.js'

       然后  use  一下,在   new Vue({ })  添加  store,   如下:

main.js部分代码

import App from './App'
import router from './router'
import store from './store/a'



Vue.config.productionTip = false

Vue.use(Vuex)
Vue.use(ElementUI);
Vue.use(MintUI)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

5、然后就可以在组件用<h2>{{this.$store.state.count}}</h2>在页面展示,下面我们来用一下。如下

        <input type="text" v-model="username" />
		
		<!--<h2>{{this.$store.state.count}}</h2>
		<button @click="login()">登陆</button>-->
		
		
		<h2>{{this.$store.state.count}}</h2>
		
		<button @click="add">增加</button>
		<button @click="jian">递减</button>

   如果要修改store数据,可通过 this.$store.commit("add"),

   修改后的数据在每个组件都生效

methods(){
 
   add(){
     this.$store.commit("add")
   }

}

-------------------------------登录后的用户名的保存-------------------------------------

 

1、下面是登录后的用户名的保存

         <input type="text" v-model="username" />
		
		<h2>{{this.$store.state.count}}</h2>
		<button @click="login()">登陆</button>



       data(){
			return{
				str:'关于',
				zidong:false,
				username:''
			}
		},

在store.js修改,b为传递的数据

var mutations={
	login(a,b){
		a.count=b
	},
	jian(a){
		a.count--
	}
}

在about页面组件更改为login

methods:{
			login(){
				this.$store.commit('login',this.username)
			}
	}

然后就可以了,这样登录名就传到了页面

《《未完待续》》

猜你喜欢

转载自blog.csdn.net/QQ_Empire/article/details/82016555
今日推荐