장 성훈

장 성훈

1614659580

제품판매웹앱 구현 - 14.카카오계정으로 로그인 및 Vuex 상태관리 구현

제품판매웹앱 구현 - 14.카카오계정으로 로그인 및 Vuex 상태관리 구현

[개발자의 품격] 품격있는 개발자 되기!

완성된 모든 코드는 깃허브에서 다운 받을 수 있습니다.
https://github.com/seungwongo/dev_dignity/tree/master/products

#vue

What is GEEK

Buddha Community

제품판매웹앱 구현 - 14.카카오계정으로 로그인 및 Vuex 상태관리 구현
장 성훈

장 성훈

1614659580

제품판매웹앱 구현 - 14.카카오계정으로 로그인 및 Vuex 상태관리 구현

제품판매웹앱 구현 - 14.카카오계정으로 로그인 및 Vuex 상태관리 구현

[개발자의 품격] 품격있는 개발자 되기!

완성된 모든 코드는 깃허브에서 다운 받을 수 있습니다.
https://github.com/seungwongo/dev_dignity/tree/master/products

#vue

Avav Smith

Avav Smith

1578555036

Simple Vuex Module to Handle Form Fields and Validations.

Simple Vuex module to handle form fields and validations.

vuex-module-validatable-state

You can build a view model for your form, which runs valdations easily. You just provide initial fields and validators to build the module, then map getters/actions to components.

Usage

Installation

$ npm i vuex-module-validatable-state

Register to core Vuex module

This module provides the function to return Vuex module as default. The function takes arguments:

  • Initial field set
  • Validators

A. Define directly

import validatableModule from "vuex-module-validatable-state";

const initialFields = {
  amount: null,
  description: "default text"
};

const validators = {
  amount: [
    ({ amount }) => amount === null ? "Require this" : false
  ],
  description: [
    ({ description }) => description.length > 15 ? "Should be shorter than 15" : false,
    ({ description, amount }) => description.indexOf(amount.toString())  ? "Should include amount" : false,
  ]
};

new Vuex.Store({
  modules: {
    myForm: {
      namespaced: true
      store,
      getters,
      actions,
      mutations,
      modules: {
        ...validatableModule(initialFields, validators) // <-- HERE
      }
    }
  }
});

B. Register to existing module

import { register } from "vuex-module-validatable-state";

const initialFields = {
  amount: null,
  description: "default text"
};

const validators = {
  amount: [
    ({ amount }) => amount === null ? "Require this" : false
  ],
  description: [
    ({ description }) => description.length > 15 ? "Should be shorter than 15" : false,
    ({ description, amount }) => description.indexOf(amount.toString())  ? "Should include amount" : false,
  ]
};

const store = new Vuex.Store({
  modules: {
    myForm: {
      namespaced: true
      store,
      getters,
      actions,
      mutations
    }
  }
});

register(store, "myForm", initialFields, validators);

Map to Components

Provided Getters

Getter name Returns
GetterTypes.ALL_FIELDS_VALID boolean whether all fields don’t have error
GetterTypes.FIELD_VALUES All fields as { [fieldName]: value }
GetterTypes.FIELD_ERRORS All errors as { [fieldName]: errorMessage }
GetterTypes.FIELD_EDITABILITIES All editable flags as { [fieldName]: editability }
GetterTypes.FIELD_DIRTINESSES All dirtiness flags as { [fieldName]: dirtiness }
GetterTypes.ANY_FIELD_CHANGED boolean whether all fields are not dirty

Provided Actions

Import ActionTypes from the module.

Action name Runs
ActionTypes.SET_FIELD Set value for a field, then runs validation if enabled
ActionTypes.SET_FIELDS_BULK Set values for fields at once, then make all dirtiness flags false
ActionTypes.RESET_FIELDS Reset values on field with initial values
ActionTypes.ENABLE_ALL_VALIDATIONS Enable interactive validation and run validations for all fields
ActionTypes.VALIDATE_FIELD_VALUE Validate specific field
ActionTypes.VALIDATE_FIELDS Validate all fields
ActionTypes.SET_FIELDS_EDITABILITY Set editability flag for a field, disabled field is not updated nor validated
ActionTypes.SET_FIELDS_PRISTINE Make all dirtiness flags false

Validators

You can pass validators when you initialize the module.

const validators = {
  amount: [/* validators for filling error against to amount */],
  description: [/* validators for filling error against to description */]
}

Each validator can take all fields values to run validation:

const validators = {
  amount: [
    ({ amount, description }) => /* return false or errorMessage */
  ]
}

Optionally, can take getters on the store which calls this module:

const validators = {
  description: [
    ({ description }, getters) => getters.getterOnStore && validationLogicIfGetterOnStoreIsTruthy(description)
  ]
}

And you can request “interactive validation” which valites every time dispatch(ActionTypes.SET_FIELD) is called

const validators = {
  amount: [
    [({ amount }, getters) => /* validator logic */, { instant: true }]
  ]
}

Provided Typings

You can import handy type/interface definitions from the module. The generic T in below expects fields type like:

interface FieldValues {
  amount: number;
  description: string;
}

getters[GetterTypes.FIELD_VALUES] returns values with following FieldValues interface.

See all typings

ValidatorTree<T>

As like ActionTree, MutationTree, you can receive type guards for Validators. By giving your fields’ type for Generics, validator can get more guards for each fields:

ValidatorTree

SetFieldAction<T>

It’s the type definition of the payload for dispatching ActionTypes.SET_FIELD, you can get type guard for your fields by giving Generics.

SetFieldAction

FieldValidationErrors<T>

Type for getters[GetterTypes.FIELD_ERRORS]

FieldEditabilities<T>

Type for getters[GetterTypes.FIELD_EDITABILITIES]

FieldDirtinesses<T>

Type for getters[GetterTypes.FIELD_DIRTINESSES]

Working Sample

Edit Sample: vuex-module-validatable-state

Registering to Vuex Store

const initialField = {
  amount: 0,
  description: null
};

const validators = {
  amount: [
    ({ amount }) => (!amount ? "Amount is required" : false),
    ({ amount }) => (amount <= 0 ? "Amount should be greater than 0" : false)
  ],
  description: [
    ({ amount, description }) =>
      amount > 1000 && !description
        ? "Description is required if amount is high"
        : false
  ]
};

const store = new Vuex.Store({
  modules: {
    ...theModule(initialField, validators)
  }
});

Mapping to Component

<template>
  <form>
    <div>
      <label for="amount">Amount (Required, Positive)</label>
      <input type="number" name="amount" v-model="amount">
      <span v-if="errors.amount">{{ errors.amount }}</span>
    </div>
    <div>
      <label for="description">Description (Required if amount is greater than 1000)</label>
      <textarea name="description" v-model="description"/>
      <span v-if="errors.description">{{ errors.description }}</span>
    </div>
    <button @click.prevent="submit">Validate and Submit</button>
  </form>
</template>

<script>
import { GetterTypes, ActionTypes } from "vuex-module-validatable-state";

export default {
  name: "App",
  computed: {
    amount: {
      get() {
        return this.$store.getters[GetterTypes.FIELD_VALUES].amount;
      },
      set(value) {
        this.$store.dispatch(ActionTypes.SET_FIELD_VALUE, {
          name: "amount",
          value
        });
      }
    },
    description: {
      get() {
        return this.$store.getters[GetterTypes.FIELD_VALUES].description;
      },
      set(value) {
        this.$store.dispatch(ActionTypes.SET_FIELD_VALUE, {
          name: "description",
          value
        });
      }
    },
    errors() {
      return this.$store.getters[GetterTypes.FIELD_ERRORS];
    }
  },
  methods: {
    submit() {
      this.$store.dispatch(ActionTypes.ENABLE_ALL_VALIDATIONS).then(() => {
        if (this.$store.getters[GetterTypes.ALL_FIELDS_VALID]) {
          alert("Form is valid, so now submitting!");
          this.$store.dispatch(ActionTypes.SET_FIELDS_PRISTINE);
        }
      });
    }
  }
};
</script>

Demo || Download


Thank for read!

#vuex #vuex-module #vue-form #vue-form-validate

Teresa  Bosco

Teresa Bosco

1599139980

Vuex Tutorial Example From Scratch

Vuex Tutorial Example From Scratch is today’s main topic. VueJS is the front end library to design the interfaces, and it is gaining immense popularity nowadays. Vuex is one of the Vue js’s model implementation, or we can say State of our data representation. So let us talk about Vuex with an example in deep. We are using Vuex 2.0 so, technically it is a Vuex 2.0 tutorial example.

Vuex 2.0 and VueJS 2.0 Tutorial will go through the practice of how you can set up the dev environment with each other, and we are creating Simple Counter Tutorial.

Purpose

One possible reason I am writing this is showcase how Vuex will play nicely together.

Requirements

For learning Vue.js, I suggest going with my this article Vuejs Tutorial With Example. It will guide you to learn fundamentals of Vue.js 2.0

#vuex #vue.js #vuex 2.0

WTF is Vuex? A Beginner's Guide To Vuex 4

Vuex is an essential tool in the Vue.js ecosystem. But developers new to Vuex may be repelled by jargon terms like “state management pattern” and confused as to what they actually need it for.

Here’s the primer on Vuex that I wish I’d had when I started learning. In it, I’ll cover the high-level concepts of Vuex and show you how to use Vuex in an app.

Table of contents:

  • Vuex
  • The problem that Vuex solves
  • Flux
  • Principle #1: single source of truth
  • Principle #2: data is read-only
  • Principle #3: mutations are synchronous
  • Cool, so what exactly is Vuex?
  • Setting up a Vuex to-do app
  • Installing Vuex
  • Creating a Vuex store
  • Adding the store to a Vue instance
  • Creating a simple app
  • Defining store state
  • Defining mutations
  • Using mutations i.e. “commits”
  • Reading store data
  • Defining getters
  • Do you actually need Vuex?

Vuex

Vuex. Is it pronounced “vewks”, or “veweks”? Or maybe it’s meant to be “vew”, pronounced with a French-style silent “x”?

My trouble with understanding Vuex only began with the name.

Being an eager Vue developer I’d heard enough about Vuex to suspect that it must be an important part of the Vue ecosystem, even if I didn’t know what it actually was.

I eventually had enough of wondering, so I went to the documentation with plans of a brief skim through; just enough to get the idea.

To my chagrin, I was greeted with unfamiliar terms like “state management pattern”, “global singleton” and “source of truth”. These terms may make sense to anyone already familiar with the concept, but for me, they didn’t gel at all.

The one thing I did get, though, was that Vuex had something to do with Flux and Redux. I didn’t know what those were either, but I figured it may help if I investigated them first.

After a bit of research and persistence, the concepts behind the jargon finally started to materialize in my mind. I was getting it. I went back to the Vuex documentation and it finally hit me…Vuex is freaking awesome!

I’m still not quite sure how to pronounce it, but Vuex has become an essential piece in my Vue.js toolbelt. I think it’s totally worth your time to check it out too, so I’ve written this primer on Vuex to give you the background that I wish I’d had.

The problem that Vuex solves

To understand Vuex it’s much easier if you first understand the problem that it’s designed to solve.

Imagine you’ve developed a multi-user chat app. The interface has a user list, private chat windows, an inbox with chat history, and a notification bar to inform users of unread messages from other users they aren’t currently viewing.

Millions of users are chatting to millions of other users through your app daily. However, there are complaints about an annoying problem: the notification bar will occasionally give false notifications. A user will be notified of a new unread message, but when they check to see what it is it’s just a message they’ve already seen.

What I’ve described is a real scenario that the Facebook developers had with their chat system a few years back. The process of solving this inspired their developers to create an application architecture they named “Flux”. Flux forms the basis of Vuex, Redux, and other similar libraries.

Flux

Facebook developers struggled with the “zombie notification” bug for some time. They eventually realized that its persistent nature was more than a simple bug - it pointed to some underlying flaw in the architecture of the app.

The flaw is most easily understood in the abstract: when you have multiple components in an application that share data, the complexity of their interconnections will increase to a point where the state of the data is no longer predictable or understandable. Consequentially the app becomes impossible to extend or maintain.

The idea of Flux was to create a set of guiding principles that describe a scalable frontend architecture that sufficiently mitigates this flaw. Not just for a chat app, but in any complex UI app with components and shared data state.

Flux is a pattern, not a library. You can’t go to Github and download Flux. It’s a design pattern like MVC. Libraries like Vuex and Redux implement the Flux pattern the same way that other frameworks implement the MVC pattern.

In fact, Vuex doesn’t implement all of Flux, just a subset. Don’t worry about that just now though, let’s instead focus on understanding the key principles that it does observe.

Principle #1: single source of truth

Components may have local data that only they need to know about. For example, the position of the scroll bar in the user list component is probably of no interest to other components.

But any data that is to be shared between components, i.e. application data, needs to be kept in a single place, separate from the components that use it.

This single location is called the “store”. Components must read application data from this location and not keep their own copy to prevent conflict or disagreement.

import { createStore } from "vuex";

// Instantiate our Vuex store
const store = createStore({

  // "State" is the application data your components
  // will subscribe to

  state () {
    return {
      myValue: 0
    };
  }
});

// Components access state from their computed properties
const MyComponent = {   
  template: "<div>{{ myValue }}</div>",
  computed: {
    myValue () {
      return store.state.myValue;
    }   
  } 
};

Principle #2: data is read-only

Components can freely read data from the store. But they cannot change data in the store, at least not directly.

Instead, they must inform the store of their intent to change the data and the store will be responsible for making those changes via a set of defined functions called “mutations”.

Why this approach? If we centralize the data-altering logic than we don’t have to look far if there are inconsistencies in the state. We’re minimizing the possibility that some random component (possibly in a third-party module) has changed the data in an unexpected fashion.

const store = createStore({ 
  state() { 
    return {
      myValue: 0
    };
  }, 
  mutations: { 
    increment (state, value) { 
      state.myValue += value;
    }
  } 
});
// Need to update a value?
// Wrong! Don't directly change a store value.
store.myValue += 10;
// Right! Call the appropriate mutation.
store.commit('increment', 10);

Principle #3: mutations are synchronous

It’s much easier to debug data inconsistencies in an app that implements the above two principles in its architecture. You could log commits and observe how the state changes in response (which you can indeed do when using Vuex with Vue Devtools).

But this ability would be undermined if our mutations were applied asynchronously. We’d know the order our commits came in, but we would not know the order in which our components committed them.

Synchronous mutations ensure state is not dependent on the sequence and timing of unpredictable events.

#vuex #vue #javascript #programming #web-development

James Ellis

James Ellis

1625640757

Pinia vs. Vuex: Is Pinia a Good Replacement for Vuex?

Compare documentation, learning curves, and use cases for the Pinia and Vuex state management libraries for your next Vue.js project.

Pinia, a lightweight state management library for Vue.js, has gained recent popularity. It uses the new reactivity system in Vue 3 to build an intuitive and fully typed state management library.

Pinia’s success can be attributed to its unique features (extensibility, store module organization, grouping of state changes, multiple stores creation, and so on) for managing stored data.

On the other hand, Vuex is also a popular state management library built for the Vue framework, and it is the recommended library for state management by the Vue core team. Vuex is highly focused on application scalability, developer ergonomics, and confidence. It is based on the same flux architecture as Redux.

In this article, we will make a comparison between Pinia and Vuex. We will analyze the setup, community strengths, and performance of both frameworks. We’ll also look at new changes in Vuex 5 compared to Pinia 2.

The code snippets used in this article are based on the Vue 3 Composition API.

#pinia #vuex #vue #vuejs