<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vuex之使用actions和axios異步初始購物車數據</title> <script src="vue.js"></script> <script src="vuex.js"></script> <script src="node_modules/axios/dist/axios.js"></script> </head> <body> <div id="demo"> <footer-cart></footer-cart> <Lists></Lists> </div> <script type="text/x-template" id="Lists"> <div> <h1 v-if="goods.length==0"> 購物車中沒有商品 <a href="">去購物吧</a> </h1> <div v-if="goods.length>0"> <table border="1"> <tr> <th>編號</th> <th>名稱</th> <th>價格</th> <th>數量</th> <th>總計</th> <th>操做</th> </tr> <tr v-for="v in goods"> <td>{{v.id}}</td> <td>{{v.title}}</td> <td>{{v.price}}</td> <td> <input type="text" v-model="v.num"> </td> <td>{{v.totalPrice}}</td> <td> <button @click="del(v.id)">刪除</button> </td> </tr> </table> </div> </div> </script> <script type="text/x-template" id="footerCart"> <div v-if="totalPrice>0"> <div> 總計:{{totalPrice}} </div> </div> </script> <script> let Lists = { template: "#Lists", computed: { goods() { return this.$store.getters.goods; } }, methods: { del(id) { this.$store.commit('del', {id}) } } } let footerCart = { template: "#footerCart", computed: { totalPrice() { return this.$store.getters.totalPrice; } } } let store = new Vuex.Store({ state: { goods: [] }, getters: { //獲取商品總價: totalPrice: state => { let totalPrice = 0; state.goods.forEach((v) => { totalPrice += v.num * v.price; }); return totalPrice; }, goods(state) { let goods = state.goods; goods.forEach((v) => { v.totalPrice = v.num * v.price; }) return goods; } }, mutations: { //刪除購物車中的商品 del(state, param) { let k; for (let i = 0; i < state.goods.length; i++) { if (state.goods[i].id == param.id) { k = i; break; } } state.goods.splice(k, 1); }, setGoods(state, param) { state.goods = param.goods; } }, actions: { loadGoods(store) { axios.get('073.php').then(function (response) { store.commit('setGoods', {goods: response.data}) //console.log(response); }) } } }); var app = new Vue({ el: "#demo", store, components: { Lists, footerCart }, mounted() { this.$store.dispatch('loadGoods'); } }); </script> </body> </html>
073.php代碼:php
<?php $data = [ ['id' => 1, 'title' => 'ihpone7', 'price' => 100, 'num' => 3], ['id' => 2, 'title' => 'ihpone8', 'price' => 200, 'num' => 4], ]; echo json_encode($data); ?>