uniapp中怎样使用vuex

1、页面中使用
 

创建store

在src目录下创建一个store文件夹,里面创建一个index.js文件,用于创建和管理vuex的store。


import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    //定义初始状态
    count: 0
  },
  mutations: {
    //定义修改状态的方法
    increment(state) {
      state.count++
    }
  }
})
export default store

组件中使用

在组件中引入store,并使用mapState、mapGetters、mapMutations等函数进行操作。


import { mapState, mapMutations } from 'vuex'
export default {
  computed: {
    ...mapState(['count'])
  },
  methods: {
    ...mapMutations(['increment'])
  }
}

在模板中使用


<template>
  <view>
    <text>count: {{count}}</text>
    <button @tap="increment">click me</button>
  </view>
</template>

在上述例子中,通过mapState将store中的count状态映射到组件的计算属性count中;通过mapMutations将store中的increment方法映射到组件的methods中。在模板中就可以方便地使用这个状态和方法了。

2、全局注册

使用vuex 需要在main.js中引入并添加到Vue的prototype原型中

import store from "./store/store.js"
Vue.prototype.$store = store

getters在界面中的使用   将会获取到vuex中state中的box属性

this.$store.getSelect();
mutations的使用   
this.$store.commit("setSelect",“新的数据”)

mutations的使用需要调用 commit方法  该方法接收两个参数  第一个是字符串   对应mutations中的方法名  表示调用mutations中的方法       第二个参数可以是任意的数据类型 第二个值将会作为参数传递进对应的调用方法;在对应的方法中获取到传递的数据后即可对state中的数据进行修改

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

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {        box:"数据",
    },
	getters:{
		getSelect(state){
			return state.box
		}
	},
	mutations: {
		setSelect(state,item){
			state.box = item
		},
	}
})

export default store

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值