Vuex demo

Vuex笔记

// store.js
import Vue from 'vue';
import Vuex from 'vuex'; //引入 vuex
import store from './store' //注册store

Vue.use(Vuex); //使用 vuex

export default new Vuex.Store({
    state: {
        // 初始化状态
        count: 0,
        someLists:[]
    },
    mutations: {
        // 处理状态
        increment(state, payload) {
            state.count += payload.step || 1;
        }
    },
    actions: {
        // 提交改变后的状态
        increment(context, param) {
            context.state.count += param.step;
            context.commit('increment', context.state.count)//提交改变后的state.count值
        },
        incrementStep({state, commit, rootState}) {
            if (rootState.count < 100) {
                store.dispatch('increment', {//调用increment()方法
                    step: 10
                })
            }
        }
    },
    getters: {
        //处理列表项
        someLists: state =>param=> {
            return state.someLists.filter(() => param.done)
        }
    }
})
//main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store' //引入状态管理 store

Vue.config.productionTip = false

new Vue({
  router,
  store,//注册store(这可以把 store 的实例注入所有的子组件)
  render: h => h(App)
}).$mount('#app')
//views/home.vue
<template>
  <div class="home">
    <!--在前端HTML页面中使用 count-->
    <HelloWorld :msg="count"/>
    <!--表单处理 双向绑定 count-->
    <input :value="count" @input="incrementStep">
  </div>
</template>

<script>
    import HelloWorld from '@/components/HelloWorld.vue'
    import {mapActions, mapState,mapGetters} from 'vuex' //注册 action 和 state

    export default {
        name: 'home',
        computed: {
            //在这里映射 store.state.count,使用方法和 computed 里的其他属性一样
            ...mapState([
                'count'
            ]),
            count () {
                return store.state.count
            }
        },
        created() {
            this.incrementStep();
        },
        methods: {
            //在这里引入 action 里的方法,使用方法和 methods 里的其他方法一样
            ...mapActions([
                'incrementStep'
            ]),
            // 使用对象展开运算符将 getter 混入 computed 对象中
            ...mapGetters([
                'someLists'
                // ...
            ])
        },
        components: {
            HelloWorld
        }
    }
</script>

运行结果下:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值