uniapp 使用 vuex demo入门,登陆实战?

首先展示一下我的目录结构:

第一步:创建store目录,并且在store目录下面创建index.js

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {// 用来缓存数据
		name: 'jack',
		isLogin: false,   //判断是否已登录
	},
	mutations: {
		// 改变isLogin的值
		setLogin(state, payload) {
			state.isLogin = payload;
		}
	}
})

export default store

第二步:在main.js里面引入:

import store from './store/index.js'
Vue.prototype.$store = store

import Vue from 'vue'
import App from './App'


##############看这里##########
// 手动引入 在index.js 上的vuex 代码
import store from './store/index.js'
Vue.prototype.$store = store
#############################

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()

第三步:创建页面:pages/login/login.vue   并且在page.json里面配置这个页面。

{
	"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
		
		{
			"path": "pages/login/login",
			"style": {
				"navigationBarTitleText": "uni-app"
			}
		}
	],
	"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "uni-app",
		"navigationBarBackgroundColor": "#F8F8F8",
		"backgroundColor": "#F8F8F8"
	}
}
<template>
	<view class="login">
		<view>
			登录状态: {{isLogin}}
		</view>
		<button type="default" @click="login">登录</button>
		<button type="default" @click="logout">注销</button>
		
		<navigator url="../index/index">首页</navigator>
	</view>
</template>

<script>
	import {mapState} from 'vuex'
	export default {
		computed: {
			...mapState(['name','isLogin'])
		},
		methods: {
			// 登录
			login() {
				this.$store.commit('setLogin', true);
			},
			// 登出 注销
			logout() {
				this.$store.commit('setLogin', false);
			}
		}
	}
</script>

<style>
</style>

最后运行:访问login页面:

总结:

  1. vuex本事是缓存,适用于将首次加载,之后不用重新加载的接口,将接口数据缓存在这里,比如登陆的状态数据,真实的登陆肯定不是这样;
  2. index.js 当中创建store(new Vuex.Store),在store里面创建state变量,修改变量需要在mutations里面创建函数,setXXX 用来修改state里面的属性;
     
  3. 别忘了在main.js里面导入注册的vuex(store/index.js)
  4. 为了在index.vue里面能使用{{}}双括号来访问name  和 isLogin 属性,我们需要在computed添加 ...mapState(['name','isLogin'])  这句话的意思是将全局注册的state展开得到name和isLogin
     
  5. this.$store.commit('setLogin', true); 因为我们已经将Vuex注册到了main.js 所以我们可以通过这样的方式调用setLogin来设置isLogin

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

orangeakon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值