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 85 86 87 88 |
<!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"></div> <input id="ipAmount" type="number" value="1"> <button id="btnIncrement">Increment</button> <button id="btnDecrement">Decrement</button> <p id="txtCount"></p> <!-- <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> --> <!-- <script src="https://unpkg.com/vuex@4/dist/vuex.global.js"></script> --> <script> const $ = document.querySelector.bind(document); //1. Tạo store Vuex const store = Vuex.createStore({ state() { return { count: 0, } }, //3. 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); } }, //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; }, }, //Getters có thể nhận 1 biến, hoặc 1 function đều được getters: { countFix: state => custom => { return state.count.toFixed(custom) } } }) // 2. Dispatch Action ==> có 2 cách viết, dispatch cả object kèm type, hoặc tách rời $('#btnIncrement').onclick = () => { let n = Number($('#ipAmount').value) //store.dispatch('increment', { amount: n }) store.dispatch({ type: 'increment', amount: n, }) } $('#btnDecrement').onclick = () => { let n = Number($('#ipAmount').value) store.dispatch('decrement', { amount: n }) } // Render lần đầu $('#txtCount').innerText = store.getters.countFix(3); //5. Subscribe state khi state thay đổi store.subscribe((mutation, state) => { //console.log(mutation, state); $('#txtCount').innerText = store.getters.countFix(3); }) </script> </body> </html> |
Vuex – Count: Without Component
Author: admin - Posted: 01/11/22 - Update: 03/11/22