计算属性
在vue开发中,有时候我们需要在页面中展示一些数据的结果或者是一些数据的相关信息,此时我们可以通过声明计算属性来声明一些新的变量,这些变量与原来的数据进行一一绑定。也就是计算属性的变量会随着data数据的改变而改变。
案例1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.min.js"></script> <script> window.onload = function(){ var vm = new Vue({ el:"#app", data:{ str1: "abcdefgh" }, computed:{ //计算属性:里面的函数都必须有返回值 str1Revs: function(){ var ret = this.str1.split("").reverse().join(""); return ret } } }); } </script> </head> <body> <div id="app"> <p>{{ str1 }}</p> <p>{{ str1Revs }}</p> </div> </body> </html>
案例2:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.13/vue.js"></script> <style> body { font-size: 14px; } table, tr, th, td { border: 1px solid red; border-collapse: collapse; /* 合并边框 */ } th, td { width: 200px; text-align: center; /* 文本水平居中 */ height: 30px; line-height: 30px; } input { width: 80px; } </style> </head> <body> <div id="app"> <table> <tr> <th>商品ID</th> <th>商品标题</th> <th>商品库存</th> <th>商品单价</th> <th>购买数量</th> <th>商品小计</th> </tr> <tr v-for="book in book_list"> <td>{{book.id}}</td> <td>《{{book.title}}》</td> <td>{{book.max_num}}</td> <td>{{book.price}}</td> <td> <button @click="sub(book)">-</button> <input type="text" v-model.number="book.num"> <button @click="add(book)">+</button> </td> <td>{{total(book)}}</td> </tr> <tr> <td colspan="4"></td> <td>总计</td> <td>{{calc}}</td> </tr> </table> </div> <script> const vm = new Vue({ el: "#app", data() { return { book_list: [ {id: 10, title: "诛仙", price: 98.50, num: 1, max_num: 7,}, {id: 110, title: "元月", price: 68.50, num: 1, max_num: 5,}, {id: 30, title: "一月", price: 108.50, num: 1, max_num: 3,}, {id: 100, title: "二月", price: 78.50, num: 1, max_num: 10,}, ] } }, // 所谓的计算属性,就是新声明一个新的变量,这个变量是经过data里面的数据运算后的结果。 computed: { calc() { let ret = 0; this.book_list.forEach((book, key) => { ret += book.price * book.num; }); return ret.toFixed(2); } }, methods: { total(book) { return (book.price * book.num).toFixed(2); }, sub(book) { // 减少数量 if (book.num > 1) { book.num -= 1; } }, add(book) { // 增加数量 if (book.num < book.max_num) { book.num += 1; } } } }) </script> </body> </html>