2023-10-27 80
效果图:
通过在输入框中写入数值进行加法计算 点击一次加号 出现一个输入框 再输入框中输入的数字会跟前面的进行叠加 减去的时候就减去输入框
hrml:
<div id="app"> <span id="result">Total: {{ totalNum }}</span> <div class="row" v-for="(item, index) in items"> <div> <div class="forms"> <input :ref="'title'" type="text" class="form-control" placeholder="How much?" v-model="item.num" /> </div> </div> </div> <button @click="addItem">+</button> <button @click="removeItem">-</button> </div>
我们先将数据中心的数据 写好 输入框的遍历通过我们items的数据进行增加 将它在row盒子上进行遍历
我们在点击加号的时候 会通过push方法向我们数据中心的数组添加num 这样input就会根据items数组中有几个num 进行增加
在dom更新的时候执行$nextTick 方法进行数组长度的处理 以及input数据处理
每当方法中心有函数被调用 在mounted中将this.addtiem调用一次
点击减号时给数组中最后一位进行删除
最后是在computed中通过reduce方法将items中的数据进行遍历 将num依次进行相加
完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>求和计算机</title> <style> * { padding: 0; margin: 0; } body { height: 100vh; display: flex; justify-content: center; align-items: center; background: palegreen; } #app { background: #714288; max-width: 300px; width: 300px; padding: 20px; border-radius: 20px; box-shadow: 0 0 10px rgba(90, 90, 90, 0.2); } .row:last-of-type { display: inline-block; } button { cursor: pointer; } #total { display: block; max-width: 300px; padding: 10px 0; font-size: 24px; color: #fff; } input { display: block; width: 100%; padding: 10px; border: none; background: #caabd8; border-radius: 5px; font-weight: bold; font-size: 18px; margin: 8px 0; box-sizing: border-box; } button { font-size: 18px; padding: 10px; box-sizing: border-box; outline: none; border: none; font-weight: bold; background-color: #ffcd60; border-radius: 5px; } </style> </head> <body> <div id="app"> <span id="result">Total: {{ totalNum }}</span> <div class="row" v-for="(item, index) in items"> <div> <div class="forms"> <input :ref="'title'" type="text" class="form-control" placeholder="How much?" v-model="item.num" /> </div> </div> </div> <button @click="addItem">+</button> <button @click="removeItem">-</button> </div> </body> </html> <script src="./js/vue.js"></script> <script> const vm = new Vue({ el: "#app", data() { return { items: [], }; }, computed: { totalNum() { return this.items.reduce((total, item) => { return total + Number(item.num); }, 0); }, }, mounted() { this.addItem(); }, methods: { addItem() { this.items.push({ num: 0, }); this.$nextTick(() => { let index = this.items.length - 1; let input = this.$refs.title[index]; input.focus(); }); }, removeItem(item) { this.items.pop(item); }, }, }); </script>
原文链接:http://1.15.94.33/?id=153
=========================================
http://1.15.94.33/ 为 “前端日记簿” 唯一官方服务平台,请勿相信其他任何渠道。
Jquery 2022-12-02
Jquery 2022-12-02
Vue 2023-06-02
Jquery 2022-12-02
Vue 2023-07-14
Vue 2023-06-02
Vue 2023-07-07
Vue 2023-07-19
Vue 2023-07-03
Vue 2023-07-26
扫码二维码
获取最新动态