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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vuex for Vue</title> </head> <body> <div id="app"> <input type="number" v-model.number="amount"> <button v-on:click="increment">Increment</button> <button v-on:click="decrement">Decrement</button> <p>{{count}}</p> </div> <script> //A. Tạo store Vuex const store = Vuex.createStore({ //3. State là kho chứa dữ liệu state() { return { count: 0, } }, //1. Action nhận dispatch, xử lý payload rồi commit mutations actions: { increment(context, payload) { context.commit('increment', payload); }, decrement(context, payload) { context.commit('decrement', payload); } }, //2. Chỉ có thể thay đổi giá trị của State tại mutations mutations: { increment(state, payload) { state.count += payload.amount; }, decrement(state, payload) { state.count -= payload.amount; }, }, //4. Getters có thể nhận 1 biến, hoặc 1 function đều được getters: { countFix: state => custom => { return state.count.toFixed(custom) } } }) //B. Tạo Root Component const RootComponent = { data() { return { amount: 1 } }, methods: { increment() { //Dispatch 1 action trên store với payload {amount} this.$store.dispatch('increment', { amount: this.amount }) }, decrement() { this.$store.dispatch('decrement', { amount: this.amount }) } }, computed: { count() { return this.$store.getters.countFix(3); } } } const app = Vue.createApp(RootComponent).use(store).mount("#app") </script> </body> </html> |
Vuex – Count: Simple Component
Author: admin - Posted: 01/11/22 - Update: 03/11/22