uni vuex使用

uniapp vuex使用

1、新建store/index.js

···
import Vue from ‘vue’
import Vuex from ‘vuex’

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		userInfo: {},
	},
	mutations: {
		setLogin(state, provider) {
			state.hasLogin = true;
			state.userInfo = provider;
			uni.setStorage({//緩存用戶登陸狀態
			    key: 'userInfo',  
			    data: provider  
			}) 
			console.log(state.userInfo);
		},
		setLogout(state) {
			state.hasLogin = false;
			state.userInfo = {};
			uni.removeStorage({  
                key: 'userInfo'  
            })
		}
	},
	actions: {
	
	}
})

export default store

···

2、在main.js中添加

···
import store from ‘./store’

Vue.protory.$store = store;

···

3、舉例在login.vue中使用

	<template>
	<view class="login-form">
		<view class="login-title">LoginForm</view>
		<view class="login-box">
			<form @submit="formSubmit"> 
				<view class="section">  
					<input class="l-input" name="userName"  placeholder="please input here" />
				</view> 
				<view class="section"> 
				
					<input class="l-input" password name="password" placeholder="please input here" />
				</view> 
				<view class="btn-area">
					<button class="l-btn" formType="submit" >登陸</button>
				</view>
			</form>
		</view>
	</view>
</template>

<script>
	import { mapMutations } from 'vuex';

	export default {
		data() {
			return {
				
			};
		},
		methods:{
			...mapMutations(['setLogin']),
			
			formSubmit(e){  
			 	this.setLogin(e.detail.value);  
			}
	 	
	}
</script>

<style lang="scss">
	...
</style>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章