Vue的学习(六)

51、vue-router之使用transition设置炫酷的路由组件过渡动画效果:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>vue-router之使用transition设置炫酷的路由组件过渡动画效果</title>
  6     <script src="./lib/vue.js"></script>
  7     <script src="./lib/vue-router.js"></script>
  8     <link href="./lib/animate.css" rel="stylesheet"/>
  9 </head>
 10 <body>
 11 <div id="app">
 12     <router-link to="/">首页</router-link>
 13     <a href="http://www.baidu.com">百度</a>
 14     <router-link to="/about">关于我们</router-link>
 15     <router-view></router-view>
 16 </div>
 17 <script type="text/x-template" id="home">
 18     <div>
 19         <li v-for="v in news">
 20             <!--只要要绑定变量,都可用v-bind: 简写 :-->
 21             <!--
 22                 .prevent: 阻止 a 标签的默认跳转行为
 23             -->
 24             <a href="" @click.prevent="go(v.id)">{{v.title}}</a>
 25         </li>
 26     </div>
 27 </script>
 28 <script type="text/x-template" id="content">
 29     <!--设置组件进入的动画-->
 30     <transition enter-active-class="animated fadeOutDown">
 31         <div>
 32             <li>{{field.title}} - {{field.id}}</li>
 33             <p>
 34                 {{field.content}}
 35             </p>
 36             <a href="" @click.prevent="back()">返回</a>
 37         </div>
 38     </transition>
 39 </script>
 40 </body>
 41 <script>
 42     const data = [
 43         {id: 1, title: 'PHP开源免费框架', content: '这是PHP的内容...'},
 44         {id: 2, title: 'CMS开源免费框架', content: '这是CMS的内容...'},
 45         {id: 3, title: '关于我们', content: '一个还不知道未来会发生什么的少年,在拼命的学习中....'}
 46     ];
 47     // 定义组件
 48     const home = {
 49         template: "#home",
 50         /*子组件的data是一个匿名函数*/
 51         data() {
 52             return {
 53                 news: data
 54             }
 55         },
 56         methods: {
 57             go(id) {
 58                 //第一种传路径的方式
 59                 //const url = "/content/" + id;
 60                 //第二种传路径的方式
 61                 // const  url = {path:'/content/'+id};
 62                 //第三种传路径的方式
 63                 const url = {name: 'content', params: {id: id}};
 64                 /*
 65                 * $route:获取参数用的
 66                 * $router:设置路由用的
 67                 * */
 68                 //push会保存历史记录
 69                 this.$router.push(url);
 70                 //replace会替换掉当前的路径
 71                 // this.$router.replace(url);
 72             }
 73         }
 74     };
 75     const content = {
 76         template: "#content",
 77         /*子组件的data是一个匿名函数*/
 78         data() {
 79             return {
 80                 field: {}
 81             }
 82         },
 83         /*
 84         * 用 watch 来监听路由,只要路由发生改变就重新加载 content 组件的内容
 85         * */
 86         watch: {
 87             '$route'(to, from) {
 88                 this.load();
 89             }
 90         },
 91         /*
 92         * mounted钩子函数的调用时机:
 93         * 编译好的HTML挂载到页面完成后执行的事件钩子,此钩子函数中一般会
 94         * 做一些ajax请求获取数据来进行数据初始化
 95         * 注意:mounted在整个实例中只执行一次
 96         * */
 97         /*
 98         * mounted的内容只在组件加载完的时候执行一次,也就是同一个组件只执行一次,不管页面后面的数据改不改变
 99         * */
100         mounted() {
101             this.load();
102         },
103         methods: {
104             load() {
105                 let id = this.$route.params.id;
106                 for (let k = 0; k < data.length; k++) {
107                     if (data[k].id == id) {
108                         this.field = data[k];
109                     }
110                 }
111             },
112             back() {
113                 /*
114                 * 如果这里使用了this.$router.go(-1),则上面的路由跳转
115                 * 就不能使用this.$router.replace(url),因为这个是替换掉路径的,没有历史记录
116                 * */
117                 /*go(-1): 返回上一页去*/
118                 this.$router.go(-1);
119             }
120         }
121     };
122     //定义路由器,然后把组件交给路由器
123     let routes = [
124         /*:id :定义了一个名为id的变量*/
125         /*路由带有变量的时候给路由一个名称,便于后面的调用*/
126         {path: '/', component: home},
127         {path: '/content/:id', component: content, name: 'content'},
128         /*alias: 定义路由的别名,是一个数组,所以可以定义多个别名*/
129         {path: '/content/3', alias: ['/about']}
130     ];
131 
132     //routes:routes可以写成routes
133     // let router = new VueRouter({routes:routes});
134     let router = new VueRouter({routes});
135     new Vue({
136         el: '#app',
137         //把路由器注入主组件中,这样才有效果
138         /*
139         * 注意:router 与 routes 的区别:
140         * router 是一个机制,相当于一个管理者,它来管理路由。
141         * routes 是一组路由,把上面的每一条路由组合起来,形成一个数组。
142         * route,它是一条路由。
143         * */
144         //如果 router的名称和router的一样可以直接写成 router 即可
145         // router: router
146         router
147     })
148 </script>
149 </html>

52、vue之vuex的使用场景分析与state购物车实例:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <script src="./lib/vue.js"></script>
  7     <script src="./lib/vuex.js"></script>
  8 </head>
  9 <body>
 10 <div id="app">
 11     <lists></lists>
 12 </div>
 13 
 14 <script type="text/x-template" id="lists">
 15     <!--必须只有一个根目录-->
 16     <div>
 17         <table border="1px" width="800px">
 18             <caption align="top">购物车</caption>
 19             <tr>
 20                 <td>编号</td>
 21                 <td>名称</td>
 22                 <td>价格</td>
 23                 <td>数量</td>
 24                 <td>总计</td>
 25             </tr>
 26             <tr v-for="v in goods">
 27                 <td>{{v.id}}</td>
 28                 <td>{{v.title}}</td>
 29                 <td>{{v.price}}</td>
 30                 <td><input type="text" v-model="v.num"/></td>
 31                 <td>{{v.totalPrice}}</td>
 32             </tr>
 33             <tr>
 34                 <td colspan="5">总价:{{totalPrice}}</td>
 35             </tr>
 36         </table>
 37     </div>
 38 </script>
 39 
 40 <script>
 41     let lists = {
 42         template: '#lists',
 43         /*computed定义的数据与data定义的数据差不多一样,只不过computed的数据是变化的*/
 44         computed: {
 45             totalPrice() {
 46                 return this.$store.getters.totalPrice;
 47             },
 48             goods() {
 49                 return this.$store.getters.goods;
 50             }
 51         }
 52     };
 53     let store = new Vuex.Store({
 54         state: {
 55             goods: [
 56                 {id: 1, title: 'iphone7Plus', price: 999, num: 2},
 57                 {id: 2, title: '华为荣耀7', price: 888, num: 3}
 58             ]
 59         },
 60         /*就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。*/
 61         getters: {
 62             // 获取商品总价
 63             // es6的写法
 64             totalPrice: state => {
 65                 let totalPrice = 0;
 66                 state.goods.forEach((v) => {
 67                     totalPrice += v.num * v.price;
 68                 });
 69                 return totalPrice;
 70             },
 71             /*
 72             * 上面的箭头函数等价于下面的,不过作用域不同,上面在箭头函数里面的 this 代表 state,而下面的函数的 this 并不是 state
 73             * totalPrice: function(state) {
 74             *   let totalPrice = 0;
 75             *   state.goods.forEach((v) => {
 76             *       totalPrice += v.num * v.price;
 77             *   });
 78             *   return totalPrice;
 79             * }
 80             *
 81             * */
 82             //获取商品并计算每件商品的总价
 83             goods(state) {
 84                 let goods = state.goods;
 85                 goods.forEach((v) => {
 86                    v.totalPrice = v.num*v.price;
 87                 });
 88                 return goods;
 89             }
 90         }
 91     });
 92     new Vue({
 93         el: '#app',
 94         //把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
 95         store,
 96         components: {
 97             lists
 98         }
 99     });
100 </script>
101 </body>
102 </html>

53、vuex之将购物车底部生成新组件用于统计总价:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>vuex之将购物车底部生成新组件用于统计总价</title>
  6     <script src="./lib/vue.js"></script>
  7     <script src="./lib/vuex.js"></script>
  8 </head>
  9 <body>
 10 <div id="app">
 11     <lists></lists>
 12     <footer-cart></footer-cart>
 13 </div>
 14 
 15 <script type="text/x-template" id="lists">
 16     <!--必须只有一个根目录-->
 17     <div>
 18         <table border="1px" width="800px">
 19             <caption align="top">购物车</caption>
 20             <tr>
 21                 <td>编号</td>
 22                 <td>名称</td>
 23                 <td>价格</td>
 24                 <td>数量</td>
 25                 <td>总计</td>
 26             </tr>
 27             <tr v-for="v in goods">
 28                 <td>{{v.id}}</td>
 29                 <td>{{v.title}}</td>
 30                 <td>{{v.price}}</td>
 31                 <td><input type="text" v-model="v.num"/></td>
 32                 <td>{{v.totalPrice}}</td>
 33             </tr>
 34         </table>
 35     </div>
 36 </script>
 37 <script type="text/x-template" id="footerCart">
 38 <div style="width: 800px; border: solid 1px red; background: green;">
 39     总计:{{totalPrice}}
 40 </div>
 41 </script>
 42 
 43 <script>
 44     let lists = {
 45         template: '#lists',
 46         /*computed定义的数据与data定义的数据差不多一样,只不过computed的数据是变化的*/
 47         computed: {
 48             goods() {
 49                 return this.$store.getters.goods;
 50             }
 51         }
 52     };
 53     let footerCart = {
 54       template: '#footerCart',
 55       computed: {
 56           totalPrice() {
 57               return this.$store.getters.totalPrice;
 58           }
 59       }
 60     };
 61     let store = new Vuex.Store({
 62         state: {
 63             goods: [
 64                 {id: 1, title: 'iphone7Plus', price: 999, num: 2},
 65                 {id: 2, title: '华为荣耀7', price: 888, num: 3}
 66             ]
 67         },
 68         /*就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。*/
 69         getters: {
 70             // 获取商品总价
 71             // es6的写法
 72             totalPrice: state => {
 73                 let totalPrice = 0;
 74                 state.goods.forEach((v) => {
 75                     totalPrice += v.num * v.price;
 76                 });
 77                 return totalPrice;
 78             },
 79             /*
 80             * 上面的箭头函数等价于下面的,不过作用域不同,上面在箭头函数里面的 this 代表 state,而下面的函数的 this 并不是 state
 81             * totalPrice: function(state) {
 82             *   let totalPrice = 0;
 83             *   state.goods.forEach((v) => {
 84             *       totalPrice += v.num * v.price;
 85             *   });
 86             *   return totalPrice;
 87             * }
 88             *
 89             * */
 90             //获取商品并计算每件商品的总价
 91             goods(state) {
 92                 let goods = state.goods;
 93                 goods.forEach((v) => {
 94                    v.totalPrice = v.num*v.price;
 95                 });
 96                 return goods;
 97             }
 98         }
 99     });
100     new Vue({
101         el: '#app',
102         //把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
103         store,
104         components: {
105             lists,footerCart
106         }
107     });
108 </script>
109 </body>
110 </html>

54、vue之使用mutations修改购物车仓库数据:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>vue之使用mutations修改购物车仓库数据</title>
  6     <script src="./lib/vue.js"></script>
  7     <script src="./lib/vuex.js"></script>
  8 </head>
  9 <body>
 10 <div id="app">
 11     <lists></lists>
 12     <footer-cart></footer-cart>
 13 </div>
 14 
 15 <script type="text/x-template" id="lists">
 16     <!--必须只有一个根目录-->
 17     <div>
 18         <div v-if="goods.length==0">亲,您的购物车没有商品了,<a href="https://www.jd.com">马上去购物吧</a></div>
 19         <div v-if="goods.length>0">
 20             <table border="1px" width="800px">
 21                 <caption align="top">购物车</caption>
 22                 <tr>
 23                     <td>编号</td>
 24                     <td>名称</td>
 25                     <td>价格</td>
 26                     <td>数量</td>
 27                     <td>总计</td>
 28                     <td>操作</td>
 29                 </tr>
 30                 <tr v-for="v in goods">
 31                     <td>{{v.id}}</td>
 32                     <td>{{v.title}}</td>
 33                     <td>{{v.price}}</td>
 34                     <td><input type="text" v-model="v.num"/></td>
 35                     <td>{{v.totalPrice}}</td>
 36                     <!--这里的 del(v.id) 调用的是子组件 lists 的方法 del-->
 37                     <td><button @click="del(v.id)">删除</button></td>
 38                 </tr>
 39             </table>
 40         </div>
 41     </div>
 42 </script>
 43 <script type="text/x-template" id="footerCart">
 44 <div style="width: 800px; border: solid 1px red; background: green;">
 45     <div v-if="totalPrice>0">
 46         总计:{{totalPrice}}
 47     </div>
 48 </div>
 49 </script>
 50 
 51 <script>
 52     let lists = {
 53         template: '#lists',
 54         /*computed定义的数据与data定义的数据差不多一样,只不过computed的数据是变化的*/
 55         computed: {
 56             goods() {
 57                 return this.$store.getters.goods;
 58             }
 59         },
 60         methods: {
 61             del(id) {
 62                 /*commit('del',{id}): 调用store里的mutations的del方法并传入参数id,参数多个的话,可以使用对象的方式,即用 {} 包裹起来*/
 63                 return this.$store.commit('del',id);
 64             }
 65         }
 66     };
 67     let footerCart = {
 68       template: '#footerCart',
 69       computed: {
 70           totalPrice() {
 71               return this.$store.getters.totalPrice;
 72           }
 73       }
 74     };
 75     let store = new Vuex.Store({
 76         //仓库
 77         state: {
 78             goods: [
 79                 {id: 1, title: 'iphone7Plus', price: 999, num: 2},
 80                 {id: 2, title: '华为荣耀7', price: 888, num: 3}
 81             ]
 82         },
 83         /*就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。*/
 84         //获取仓库数据,可以对获取的数据处理
 85         getters: {
 86             // 获取商品总价
 87             // es6的写法
 88             totalPrice: state => {
 89                 let totalPrice = 0;
 90                 state.goods.forEach((v) => {
 91                     totalPrice += v.num * v.price;
 92                 });
 93                 return totalPrice;
 94             },
 95             /*
 96             * 上面的箭头函数等价于下面的,不过作用域不同,上面在箭头函数里面的 this 代表 state,而下面的函数的 this 并不是 state
 97             * totalPrice: function(state) {
 98             *   let totalPrice = 0;
 99             *   state.goods.forEach((v) => {
100             *       totalPrice += v.num * v.price;
101             *   });
102             *   return totalPrice;
103             * }
104             *
105             * */
106             //获取商品并计算每件商品的总价
107             goods(state) {
108                 let goods = state.goods;
109                 goods.forEach((v) => {
110                    v.totalPrice = v.num*v.price;
111                 });
112                 return goods;
113             }
114         },
115         //修改仓库的商品
116         mutations: {
117             //删除购物车中的商品
118             del(state,param) {
119                 let good;
120                 for (let i=0; i<state.goods.length; i++) {
121                     if (state.goods[i].id==param.id) {
122                         good = i;
123                     }
124                 }
125                 state.goods.splice(good,1);
126             }
127         }
128     });
129     new Vue({
130         el: '#app',
131         //把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
132         store,
133         components: {
134             lists,footerCart
135         }
136     });
137 </script>
138 </body>
139 </html>

55、vuex之使用actions与axios异步初始化购物车数据:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>vue之使用mutations修改购物车仓库数据</title>
  6     <script src="./lib/vue.js"></script>
  7     <script src="./lib/vuex.js"></script>
  8     <script src="./lib/axios.js"></script>
  9 </head>
 10 <body>
 11 <div id="app">
 12     <lists></lists>
 13     <footer-cart></footer-cart>
 14 </div>
 15 
 16 <script type="text/x-template" id="lists">
 17     <!--必须只有一个根目录-->
 18     <div>
 19         <div v-if="goods.length==0">亲,您的购物车没有商品了,<a href="https://www.jd.com">马上去购物吧</a></div>
 20         <div v-if="goods.length>0">
 21             <table border="1px" width="800px">
 22                 <caption align="top">购物车</caption>
 23                 <tr>
 24                     <td>编号</td>
 25                     <td>名称</td>
 26                     <td>价格</td>
 27                     <td>数量</td>
 28                     <td>总计</td>
 29                     <td>操作</td>
 30                 </tr>
 31                 <tr v-for="v in goods">
 32                     <td>{{v.id}}</td>
 33                     <td>{{v.title}}</td>
 34                     <td>{{v.price}}</td>
 35                     <td><input type="text" v-model="v.num"/></td>
 36                     <td>{{v.totalPrice}}</td>
 37                     <!--这里的 del(v.id) 调用的是子组件 lists 的方法 del-->
 38                     <td><button @click="del(v.id)">删除</button></td>
 39                 </tr>
 40             </table>
 41         </div>
 42     </div>
 43 </script>
 44 <script type="text/x-template" id="footerCart">
 45 <div style="width: 800px; border: solid 1px red; background: green;">
 46     <div v-if="totalPrice>0">
 47         总计:{{totalPrice}}
 48     </div>
 49 </div>
 50 </script>
 51 
 52 <script>
 53     let lists = {
 54         template: '#lists',
 55         /*computed定义的数据与data定义的数据差不多一样,只不过computed的数据是变化的*/
 56         computed: {
 57             goods() {
 58                 return this.$store.getters.goods;
 59             }
 60         },
 61         methods: {
 62             del(id) {
 63                 /*commit('del',{id}): 调用store里的mutations的del方法并传入参数id,参数多个的话,可以使用对象的方式,即用 {} 包裹起来*/
 64                 //commit是触发mutations
 65                 return this.$store.commit('del',id);
 66             }
 67         }
 68     };
 69     let footerCart = {
 70       template: '#footerCart',
 71       computed: {
 72           totalPrice() {
 73               return this.$store.getters.totalPrice;
 74           }
 75       }
 76     };
 77     let store = new Vuex.Store({
 78         //仓库
 79         state: {
 80             goods: []
 81         },
 82         /*就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。*/
 83         //获取仓库数据,可以对获取的数据处理
 84         getters: {
 85             // 获取商品总价
 86             // es6的写法
 87             totalPrice: state => {
 88                 let totalPrice = 0;
 89                 state.goods.forEach((v) => {
 90                     totalPrice += v.num * v.price;
 91                 });
 92                 return totalPrice;
 93             },
 94             /*
 95             * 上面的箭头函数等价于下面的,不过作用域不同,上面在箭头函数里面的 this 代表 state,而下面的函数的 this 并不是 state
 96             * totalPrice: function(state) {
 97             *   let totalPrice = 0;
 98             *   state.goods.forEach((v) => {
 99             *       totalPrice += v.num * v.price;
100             *   });
101             *   return totalPrice;
102             * }
103             *
104             * */
105             //获取商品并计算每件商品的总价
106             goods(state) {
107                 let goods = state.goods;
108                 goods.forEach((v) => {
109                    v.totalPrice = v.num*v.price;
110                 });
111                 return goods;
112             }
113         },
114         //修改仓库的商品
115         mutations: {
116             //删除购物车中的商品
117             del(state,param) {
118                 let good;
119                 for (let i=0; i<state.goods.length; i++) {
120                     if (state.goods[i].id==param.id) {
121                         good = i;
122                     }
123                 }
124                 state.goods.splice(good,1);
125             },
126             setGoods(state,param) {
127                 state.goods = param.goods;
128             }
129         },
130         //从后台抓取数据
131         actions: {
132             loadGoods(store) {
133                 axios.get('55.php').then(function (response) {
134                     store.commit('setGoods',{goods:response.data})
135                 })
136             }
137         }
138     });
139     new Vue({
140         el: '#app',
141         //把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
142         store,
143         components: {
144             lists,footerCart
145         },
146         mounted() {
147             //dispatch是触发actions的
148             //调用actions里的loadGoods方法
149             this.$store.dispatch('loadGoods');
150         }
151     });
152 </script>
153 </body>
154 </html>

56、vuex之模块化modules开发实例:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>vuex之模块化modules开发实例</title>
  6     <script src="./lib/vue.js"></script>
  7     <script src="./lib/vuex.js"></script>
  8     <script src="./lib/axios.js"></script>
  9 </head>
 10 <body>
 11 <div id="app">
 12     <lists></lists>
 13     <footer-cart></footer-cart>
 14 </div>
 15 
 16 <script type="text/x-template" id="lists">
 17     <!--必须只有一个根目录-->
 18     <div>
 19         <div v-if="goods.length==0">亲,您的购物车没有商品了,<a href="https://www.jd.com">马上去购物吧</a></div>
 20         <div v-if="goods.length>0">
 21             <table border="1px" width="800px">
 22                 <caption align="top">购物车</caption>
 23                 <tr>
 24                     <td>编号</td>
 25                     <td>名称</td>
 26                     <td>价格</td>
 27                     <td>数量</td>
 28                     <td>总计</td>
 29                     <td>操作</td>
 30                 </tr>
 31                 <tr v-for="v in goods">
 32                     <td>{{v.id}}</td>
 33                     <td>{{v.title}}</td>
 34                     <td>{{v.price}}</td>
 35                     <td><input type="text" v-model="v.num"/></td>
 36                     <td>{{v.totalPrice}}</td>
 37                     <!--这里的 del(v.id) 调用的是子组件 lists 的方法 del-->
 38                     <td><button @click="del(v.id)">删除</button></td>
 39                 </tr>
 40             </table>
 41         </div>
 42     </div>
 43 </script>
 44 <script type="text/x-template" id="footerCart">
 45 <div style="width: 800px; border: solid 1px red; background: green;">
 46     <div v-if="totalPrice>0">
 47         总计:{{totalPrice}}
 48     </div>
 49 </div>
 50 </script>
 51 
 52 <script>
 53     let lists = {
 54         template: '#lists',
 55         /*computed定义的数据与data定义的数据差不多一样,只不过computed的数据是变化的*/
 56         computed: {
 57             goods() {
 58                 console.log(this.$store.state.cart.goods);
 59                 return this.$store.getters['cart/goods'];
 60             }
 61         },
 62         methods: {
 63             del(id) {
 64                 /*commit('del',{id}): 调用store里的mutations的del方法并传入参数id,参数多个的话,可以使用对象的方式,即用 {} 包裹起来*/
 65                 //commit是触发mutations
 66                 return this.$store.commit('cart/del',id);
 67             }
 68         }
 69     };
 70     let footerCart = {
 71       template: '#footerCart',
 72       computed: {
 73           totalPrice() {
 74               return this.$store.getters['cart/totalPrice'];
 75           }
 76       }
 77     };
 78     //定义一个购物车模块
 79     const cartModule = {
 80         namespaced: true,
 81         //在没有定义 namespaced: true 之前,state 是局部的,其调用方式为:this.$store.state.cart.goods ,其他的都是全局的,所有调用方式不变
 82         //定义后:获取getters中的goods => this.$store.getters['cart/goods']
 83         //仓库
 84         state: {
 85             goods: [
 86                 {id: 1, title: 'iphone7Plus', price: 999, num: 2},
 87                 {id: 2, title: '华为荣耀7', price: 888, num: 3}
 88             ]
 89         },
 90         /*就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。*/
 91         //获取仓库数据,可以对获取的数据处理
 92         getters: {
 93             // 获取商品总价
 94             // es6的写法
 95             totalPrice: state => {
 96                 let totalPrice = 0;
 97                 state.goods.forEach((v) => {
 98                     totalPrice += v.num * v.price;
 99                 });
100                 return totalPrice;
101             },
102             /*
103             * 上面的箭头函数等价于下面的,不过作用域不同,上面在箭头函数里面的 this 代表 state,而下面的函数的 this 并不是 state
104             * totalPrice: function(state) {
105             *   let totalPrice = 0;
106             *   state.goods.forEach((v) => {
107             *       totalPrice += v.num * v.price;
108             *   });
109             *   return totalPrice;
110             * }
111             *
112             * */
113             //获取商品并计算每件商品的总价
114             goods(state) {
115                 let goods = state.goods;
116                 goods.forEach((v) => {
117                     v.totalPrice = v.num*v.price;
118                 });
119                 return goods;
120             }
121         },
122         //修改仓库的商品
123         mutations: {
124             //删除购物车中的商品
125             del(state,param) {
126                 let good;
127                 for (let i=0; i<state.goods.length; i++) {
128                     if (state.goods[i].id==param.id) {
129                         good = i;
130                     }
131                 }
132                 state.goods.splice(good,1);
133             }/*,
134             setGoods(state,param) {
135                 state.goods = param.goods;
136             }*/
137         }/*,
138         //从后台抓取数据
139         actions: {
140             loadGoods(store) {
141                 axios.get('55.php').then(function (response) {
142                     store.commit('setGoods',{goods:response.data})
143                 })
144             }
145         }*/
146     };
147     let store = new Vuex.Store({
148       modules: {
149           cart: cartModule
150       }
151     });
152     new Vue({
153         el: '#app',
154         //把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
155         store,
156         components: {
157             lists,footerCart
158         }/*,
159         mounted() {
160             //dispatch是触发actions的
161             //调用actions里的loadGoods方法
162             this.$store.dispatch('loadGoods');
163         }*/
164     });
165 </script>
166 </body>
167 </html>

57、配置 vue 项目请求 java 后端项目:

主要修改:config/index.js 文件

 1 'use strict'
 2 // Template version: 1.3.1
 3 // see http://vuejs-templates.github.io/webpack for documentation.
 4 
 5 const path = require('path')
 6 
 7 module.exports = {
 8   dev: {
 9 
10     // Paths
11     assetsSubDirectory: 'static',
12     assetsPublicPath: '/',
13     //路由接口代理配置
14     proxyTable: {
15       '/api': {
16         target: 'http://localhost:8443',   // 后端项目的访问根路径
17         changeOrigin: true,
18         pathRewrite: {
19           '^/api': ''
20         }
21       }
22     },
23 
24     // Various Dev Server settings
25     host: 'localhost', // can be overwritten by process.env.HOST
26     port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
27     autoOpenBrowser: false,
28     errorOverlay: true,
29     notifyOnErrors: true,
30     poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
31 
32 
33     /**
34      * Source Maps
35      */
36 
37     // https://webpack.js.org/configuration/devtool/#development
38     devtool: 'cheap-module-eval-source-map',
39 
40     // If you have problems debugging vue-files in devtools,
41     // set this to false - it *may* help
42     // https://vue-loader.vuejs.org/en/options.html#cachebusting
43     cacheBusting: true,
44 
45     cssSourceMap: true
46   },
47 
48   build: {
49     // Template for index.html
50     index: path.resolve(__dirname, '../dist/index.html'),
51 
52     // Paths
53     assetsRoot: path.resolve(__dirname, '../dist'),
54     assetsSubDirectory: 'static',
55     assetsPublicPath: '/',
56 
57     /**
58      * Source Maps
59      */
60 
61     productionSourceMap: true,
62     // https://webpack.js.org/configuration/devtool/#production
63     devtool: '#source-map',
64 
65     // Gzip off by default as many popular static hosts such as
66     // Surge or Netlify already gzip all static assets for you.
67     // Before setting to `true`, make sure to:
68     // npm install --save-dev compression-webpack-plugin
69     productionGzip: false,
70     productionGzipExtensions: ['js', 'css'],
71 
72     // Run the build command with an extra argument to
73     // View the bundle analyzer report after build finishes:
74     // `npm run build --report`
75     // Set to `true` or `false` to always turn it on or off
76     bundleAnalyzerReport: process.env.npm_config_report
77   }
78 }

main.js 文件:

 1 // The Vue build version to load with the `import` command
 2 // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
 3 import Vue from 'vue'
 4 import App from './App'
 5 import router from './router'
 6 import axios from 'axios'
 7 //设置反向代理,前端请求默认发送到 http://localhost:8443/api
 8 axios.defaults.baseURL = 'http://localhost:8443/api';
 9 //将 API 方法绑定到全局
10 Vue.prototype.$axios = axios;
11 
12 Vue.config.productionTip = false;
13 
14 /* eslint-disable no-new */
15 new Vue({
16   el: '#app',
17   router,
18   components: { App },
19   template: '<App/>'
20 });

springboot 的 controller 的配置:

 1 package com.mgy.controller;
 2 
 3 import com.mgy.pojo.VueLoginInfoVo;
 4 import com.mgy.result.Result;
 5 import javax.validation.Valid;
 6 
 7 import org.springframework.stereotype.Controller;
 8 import org.springframework.web.bind.annotation.*;
 9 import org.springframework.web.util.HtmlUtils;
10 
11 import java.util.Objects;
12 
13 /**
14  * @author MGY
15  * @data 2020/1/5 19:33
16  */
17 @Controller
18 public class LoginController {
19 
20     /**
21      * 登录控制器,前后端分离用的不同协议和端口,所以需要加入 @CrossOrigin 支持跨域。
22      * @param vueLoginInfoVo
23      * @return
24      */
25     @CrossOrigin
26     @PostMapping(value = "/api/login")
27     @ResponseBody
28     public Result login(@Valid @RequestBody VueLoginInfoVo vueLoginInfoVo) {
29         // 对 html 标签进行转义,防止 XSS 攻击
30         String username = vueLoginInfoVo.getUsername();
31         username = HtmlUtils.htmlEscape(username);
32 
33         if (!Objects.equals("admin", username) || !Objects.equals("123456", vueLoginInfoVo.getPassword())) {
34             String message = "账号密码错误";
35             System.out.println("test");
36             return new Result(400);
37         } else {
38             return new Result(200);
39         }
40     }
41 }

配置文件 application.properties :

 1 server.port=8443 

猜你喜欢

转载自www.cnblogs.com/maigy/p/12150692.html