State and reactivity in Vue

栏目: IT技术 · 发布时间: 5年前

内容简介:In one of myprevious articles, I mentioned how it is possible to design a simple state manager in Vue by usingIn Vue 2, a reactive store might look like this:We can provide the components with a basic

In one of myprevious articles, I mentioned how it is possible to design a simple state manager in Vue by using observable . The Observable API has been available in Vue since version 2 however, with version 3 the reactive object is no longer directly modified but proxied into. Let's have a look how both work in detail:

In Vue 2, a reactive store might look like this:

// store.js
export const store = Vue.observable({ orders: 0 });

We can provide the components with a basic dispatch function that will collect an action with a payload and that will take care of updating the state. Also, we might want to provide a getters helper so that the store values can be reached as computed properties:

// store.js
export function dispatch(type, payload) {
    switch(type) {
        case 'increment-orders':
            Object.assign(store, { orders: store.orders + payload });
            break;
        default:
            //
    }
}

export function getters(orders) {
    return {
        orders: () => store.orders
    }
}

In our Vue component, we register the getters and use dispatch to notify the store about a user event:

<template>
    I have {{ orders }} orders on my account. 
    <a @click="increment()">add order</a>
</template>

<script>
import { dispatch } from 'store';

return {
    computed: { ...getters() },
    methods: { 
        increment() {
            dispatch('increment-orders', 1); 
        } 
    }
};
</script>

Vue 3 and the Composition API

With the introduction of the Composition API , operating with reactive properties is much simpler. The above example could be easily refactored to follow the new constructs. Here, reactive replaced the functionaltiy that observable was providing:

// store.js
import { reactive } from 'vue';

export const store = reactive({ orders: 0 });

// Component.vue
import { store, dispatch } from './store';

export default {
    setup() {
        return { store };
    },
    methods:{
        increment() {
            dispatch('increment-orders', 1);
        }
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

左手打工,右手创业

左手打工,右手创业

韩垒 / 东北师大 / 2011-4 / 29.80元

《左手打工右手创业》内容简介:打工一族,不能没有激情,不能没有梦想,激情能让你战胜困难,勇往直前;同时,要让梦想变成现实,你还必须具备务实的态度和实干的精神,一步一步向目标前进。创业不是简单的乌托邦式的理想,不是仅凭一腔热血加美好梦想就能顺利到达胜利的彼岸。个人创业更多的是要依靠前期科学的规划、多角度的观察、理性的分析、有效的资源分析与整合、成熟高效的运作技能、良好的商业心态等。 《左手打工......一起来看看 《左手打工,右手创业》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具