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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
| <!DOCTYPE html> <html> <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>计算属性的使用</title> <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.2.47/vue.global.prod.js"></script> <style type="text/css"> table.gridtable { font-family: verdana, arial, sans-serif; font-size: 11px; color: #333333; border-width: 1px; border-color: #666666; border-collapse: collapse; margin: 20px auto; width: 280px; } table.gridtable th { border-width: 1px; padding: 8px; border-style: solid; border-color: #666666; background-color: #dedede; } table.gridtable td { border-width: 1px; padding: 8px; border-style: solid; border-color: #666666; background-color: #ffffff; } table th:nth-child(1){ width: 65px; } </style> </head> <body> <div id="app"> <table class="gridtable"> <tr> <th colspan="2"> 学生姓名 </th> </tr> <tr> <td> FirstName </td> <td> <input type="text" v-model="firstNa"/> </td> </tr> <tr> <td> LastName </td> <td> <input type="text" v-model="lastNa"/> </td> </tr> <tr> <td> FullName </td> <td> <input type="text" v-model.lazy="fullName"/> <!-- .lazy 懒加载--> </td> </tr> </table> <table class="gridtable"> <tr> <th>学科</th> <th>分数</th> </tr> <tr> <td>语文</td> <td><input type="text" v-model.number="chinese"/></td> </tr> <tr> <td>数学</td> <td><input type="text" v-model.number="math"/></td> </tr> <tr> <td>英语</td> <td><input type="text" v-model.number="english"/></td> </tr> <tr> <td>总分</td> <td><input type="text" v-model="getSums" readonly/></td> </tr> <tr> <td>平均分</td> <td><input type="text" v-model="getAverage" /></td> </tr> </table>
</div> <script> const app = Vue.createApp({ data() { return { lastNa:"", firstNa:"", chinese: 0, math: 0, english: 0, }; }, // 计算属性 用来计算数据的 用来代替methods 但是计算属性有缓存 set方法可以用来监听数据的变化 用来代替watch computed: { getAverage() { return (this.chinese + this.math + this.english) / 3; }, getSums() { return this.chinese + this.math + this.english; }, // fullName() { // // return this.firstNa +" "+ this.lastNa; // return `${this.firstNa} ${this.lastNa}`; // // `` 模板字符串 ES6 新增 用来拼接字符串 用${}来拼接变量 用来代替+号 // } fullName: { get() { return `${this.firstNa} ${this.lastNa}`; }, set(value) { const names = value.split(" "); console.log(names); this.firstNa = names[1]; this.lastNa = names[names.length-1]; // .lazy 修饰符 用来监听数据的变化 用来代替watch } } }, methods: {
}, }).mount("#app"); </script> </body> </html>
|