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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.0/vuex.js"></script> </head> <body> <div id="app"> <ul> <li v-for="(item,index) in list" :key="index">{{ item }}</li> </ul> 共 {{ listCount }} 筆資料 <button @click="getCountryList">getCountryList</button> <button @click="getNumberList">getNumberList</button> </div>
<script> const ENUMS = { List: { Number: "GetNumberList", Country: "GetCountryList" } };
function postData(url, data) { return fetch(url, { body: JSON.stringify(data), cache: "no-cache", credentials: "same-origin", headers: { "content-type": "application/json" }, method: "POST", mode: "cors", redirect: "follow", referrer: "no-referrer" }).then(response => response.json()); }
const store = new Vuex.Store({ state: { list: [], dataSets:[ paymentInfoDataSet:[] ] }, actions:{ getPaymentDetail({ commit }, { paymentId, url }) { postData(url, { paymentId: paymentId }) .then(response => { commit("updatePaymentInfo", { paymentId: paymentId, info: response }); }) }, }, mutations: { [ENUMS.List.Number](state, list) { state.list = [...list]; }, [ENUMS.List.Country](state, list) { state.list = [...list]; }, ["updatePaymentInfo"](state, detail) { let newDataSet = [...dataSets.paymentInfoDataSet]; let currentData = state.dataSets.paymentInfoDataSet.find(x => x.paymentId === detail.paymentId); if (currentData) { let removeIndex = newDataSet.findIndex(function(item) { return item.paymentId === detail.paymentId; }); newDataSet.splice(removeIndex, 1); } newDataSet.push(detail); state.dataSets.paymentInfoDataSet = newDataSet; }, }, getters: { currentList(state) { return state.list; }, currentListCount(state, getters) { return getters.currentList.length; } } });
new Vue({ el: "#app", store, data: { defList: ["american", "chinese", "japaneses", "europe", "africa"], numberList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }, computed: { list() { return this.$store.getters.currentList; }, listCount() { return this.$store.getters.currentListCount; } }, methods: { getCountryList() { store.commit(ENUMS.List.Country, this.defList); }, getNumberList() { store.commit(ENUMS.List.Number, this.numberList); } } }); </script> </body> </html>
|