-- Có thể hiểu đơn giản như các OOP khác
-- state giống như nơi lưu trữ biến
-- getters: giống như getter -> là nơi gọi biến
-- mutations: giống như settter -> là nơi set các biến
1. Store
-- Store là nơi chứa dữ liệu, bao gồm sate (giống biến toàn cục và có thể reactively) và getter
-- File ./src/store/store.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import Vue from 'vue'; import Vuex from 'vuex' Vue.use(Vuex) export const store = new Vuex.Store({ state: { customNumber: 0 }, getters: { //Biến (state) chính là lấy (state) của store multil10: state => { return state.customNumber * 10; }, //Biến (state, getters) chính là lấy (state, getters) của store multil11: (state, getters) => { return state.customNumber + getters.multil10; }, //Có thể return ra 1 hàm để tiếp tục tùy chỉnh getters, trường hợp này là tùy chỉnh fixed fixNumberVND: (state, getters) => (fixed = 2) => { return state.customNumber.toFixed(fixed); }, }, mutations: { increment(state, payload){ state.customNumber += payload; } } }) |
2. Components
-- Có thể gọi state, computed và mutations thoải con gà mái bằng nhiều cách
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<template> <div> <div> <span>Có thể tùy chỉnh trực tiếp các biến state</span> <button @click="$store.state.customNumber++">Cộng 1</button> <button @click="$store.state.customNumber--">Trừ 1</button> </div> <p> Có thể lấy trực tiếp state "customNumber": {{ $store.state.customNumber }} </p> <p> Có thể lấy trực tiếp getters "multil10": {{ $store.getters.multil10 }} </p> <br /> <p>Có thể lấy từ computed "multil10": {{ multil10 }}</p> <p>Có thể lấy từ computed "x11": {{ x11 }}</p> <p> Có thể lấy từ computed "fixtoVND": {{ fixtoVND }} </p> <div> <span>Có thể gọi trực tiếp mutations "increment"</span> <button @click="$store.commit('increment', 5)">Increment 5</button ><br /> <span>Có thể gọi method "decrement" từ mapMutations</span> <button @click="decrement(5)">Decrement 5</button> </div> </div> </template> <script> //có thể dùng mapGetter để gọi các getter trong store 1 cách ngắn gọn import { mapGetters } from "vuex"; import { mapMutations } from "vuex"; export default { computed: { //có thể gọi trực tiếp tên các getter bằng mảng ...mapGetters(["multil10", "multil11"]), //cũng có thể gọi và thay thế bằng các tên khác ...mapGetters({ x10: "multil10", x11: "multil11", }), //các hàm khác của computed vẫn gọi và sử dụng bình thường fixtoVND() { return this.$store.getters.fixNumberVND(3); }, }, methods: { ...mapMutations(["increment", "decrement"]), }, }; </script> |