VUEX简单实现

1、先看一个vue响应式的例子,vue中的data 、methods、computed,可以实现响应式。

视图通过点击事件,触发methods中的increment方法,可以更改state中count的值,一旦count值发生变化,computed中的函数能够把getCount更新到视图。

<div id="app">
    <button @click="increment"></button>
    {{getcount}}
</div>
new Vue({
    el: "#app",
    // state
    data () {
     return {
        count: 0
     }
    },
     // view
    computed: {
        getCount(){
            return this.count
        }
    },
    // actions
    methods: {
     increment () {
        this.count++
     }
    },
})

2、我们可以用vuex实现和vue同样的响应式功能。

其实他们原理时一样的,vuex中也有四个属性值:state、getters、mutations、actions。。

在没有actions的情况下:

数据:state --> data
获取数据:getters --> computed
更改数据:mutations --> methods
视图通过点击事件,触发mutations中方法,可以更改state中的数据,一旦state数据发生更改,getters把数据反映到视图。

那么actions,可以理解处理异步,而单纯多加的一层。

既然提到了mutions actions这时候 就不得不提commit,dispatch这两个有什么作用呢?

在vue例子中,通过click事件,触发methods中的方法。当存在异步时,而在vuex中需要dispatch来触发actions中的方法,actions中的commit可以触发mutations中的方法。同步,则直接在组件中commit触发vuex中mutations中的方法。

下面我们看下vuex中能像vue中实现改变状态,更新视图的功能:

Vuex.js

const store =  new Vuex.Store({
    
    state: {
        count: 0
    },
    
    //state的值只能通过mutations来修改
    mutations: {
        increment(state) {
            state.count++
        }
    },
    
   //this.$store.commit("increment")触发mutations中函数"increment"
    actions: {
        increment({commit}) {
             commit("increment"); //this.$store.commit("increment")
        }
     
    },
    
   //通过getter中的方法来获取state值
    getters: {
        getCount(state) {
            return state.count
        }
    }
    })
     
    export default store

App.vue

 <template>
    <div id="app">
            <button @click="increment">增加</button>
            <!-- 有时候不能直接 强制使用store里面的状态 this.$store.state.count -->
            {{this.$store.getters.getCount}}
    </div>
    </template>
     
    <script>
    export default {
        methods: {
        increment(){
                //this.$store.dispatch("increment")触发actions函数"increment"
                this.$store.dispatch("increment")
            }
        }
    }
    </script>

搞定!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值