vuex使用

在这里插入图片描述

import Vue from 'vue'
 
import Vuex from 'vuex'
 
Vue.use(Vuex)
// 方法1(直接写)
const store = new Vuex.Store({
    state: {
		//公共的变量,这里的变量不能随便修改,只能通过触发mutations的方法才能改变
	    text1: 1
    },
    getters: {
        // state的计算属性
        get1: state => {
            return state.text1 + 1
        },
        get2: (state, getters) => {
            //state :可以访问数据
            //getters:访问其他函数,等同于 store.getters
            return getters.get1
        },
        getTodoById: (state) => (value) => {
            return state.text1 + value
        }
    },
    mutations: {
		//相当于同步的操作
        //传递数值
        add(state, n) {
            state.text1 += n
        }
        //传递对象类型
        add(state, payload) {
            state.text1 += payload.value
        }
	},
    actions: {
		//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变
        addCountAction (context , payload) {
            context.commit('add',payload)
        }
	}
})
export default store
// 方法二(分模块)
// 如果将store分成一个个的模块的话,则需要用到modules。
//然后在每一个module中写state, getters, mutations, actions等。
import cart from '@/store/modules/cart.js'
export default new Vuex.Store({
	
	modules:{
		cart
	}
})

在这里插入图片描述
三、使用

第一种方式:this. s t o r e 直 接 操 作 例 如 当 取 值 : 直 接 在 页 面 中 使 用 t h i s . store直接操作 例如当取值:直接在页面中使用this. store使this.store.state.变量名

第二种方法:mapState, mapGetters, mapActions, mapMutations

<template>
    <view class="content">
    
    </view>
</template>
 
<script>
    import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
    import store from '@/store/index.js';
//导入
    export default {
        data() {
            return {
            }
        },
        computed: { 
//computed中注册
            ...mapGetters(['get1']),
// 不用modules对应写法
            ...mapState([
                'text1'
            ])
// 用modules对应写法
            ...mapState({
				text1:state=>state.cart.text1
			})
        }
        methods: {
            ...mapMutations(['add']),
            ...mapActions(['addCountAction'])
// 下面示例调用各种方法,就直接用store了
// getters
            this.$store.getters.get1
// mutations
            store.commit('add')
// actions   以对象形式分发
            store.dispatch({
                type: 'addCountAction',
                amount: 5
            })
        }
    }
</script>
 
<style>
</style>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值