在 React 跟 Vue 中我们可以较为轻松的利用资料 来做 render 对应的话画面生出来
不用像 Jquery 时期 , 改变资料时 , 需要将对应的 dom 做修改 , 有时还会发生这里改了 , 那里忘记改的状况
举个例子来说 , 下方有个商业的案例 , 来控制 按钮
的显示
在 Jquery 我们可能会这样写 Code
// .btn = 按钮 / cost = 花费点数 / left = 储值点数
let cost = 0 , left = 500
function costChange() {
if ( cost > left ) $('.btn').css({backgroundColor:'gary'}).prop('disabled',true)
else if ( cost === left ) $('.btn').css({backgroundColor:'orange'})
else $('.btn').css({backgroundColor:'green'})
}
function addCost(amount) {
cost += amount
costChange()
}
function minusCost(amount) {
cost -= amount
costChange()
}
初看 Code 时 , 会觉得蛮正常的 , 就是直接将文字描述都转换成 Jquery Code ,
可是当客户在调整购买项目 (多买一个法帐 . 少买一个套装) 後 , 就会发现按钮不能点 , 无法购买
这时我们才想到 , 客户买超过後 , 再将东西扣回来 , 我们需要将那个 disabled 给拿掉
然後我们再改版 Code , 购买金额减少时 , 将 disabled 拿掉
// .btn = 按钮 / cost = 花费点数 / left = 储值点数
function costChange(cost , left) {
if ( cost > left ) $('.btn').css({backgroundColor:'gary'}).prop('disabled',true)
else if ( cost === left ) $('.btn').css({backgroundColor:'orange'}).prop('disabled',false)
else $('.btn').css({backgroundColor:'green'}).prop('disabled',false)
}
当我们以为天下太平时 , 客户投诉了 < 为何我家小孩可以用我的点数买东西 >
阿 ! 当初忘了加上登入机制 ,
变成同一台电脑的使用者 , 就可以消费点数 , 让随便人都可以花使用者的剩余点数 ,
我们补上个登入状态吧
// .btn = 按钮
function login() {
$('.btn').prop('disabled',false)
}
function logout() {
$('.btn').prop('disabled',true)
}
登出後 , 不能买东西 , 运作正常 ,
可是先将要买的东西塞满 , 再登入 , 奇怪 可以买东西 我们利用这个 BUG 将东西买好买满吧
然後 , 我们需要在登入时 , 多传入与判断 花费点数 & 储值点数
这种与登入登出无关的参数
// .btn = 按钮
function login(cost , left) {
if ( cost > left ) $('.btn').prop('disabled',true)
else $('.btn').prop('disabled',false)
costChange()
}
这时我们就会发现 , 在按钮的状态控制上 , 利用 Jquery 直接改变 DOM 的行为 , 好像不是个好做法
那如果在 Vue 中会如何处理呢 ?
<template>
<button :style="{backgroundColor:bgColor}" :disabled="disabled">购买</button>
</template>
<script>
export default {
methods: {
login() {
this.isLogin = true
},
logout() {
this.isLogin = false
},
addCost(amount) {
this.cost += amount
},
minusCost(amount) {
this.cost -= amount
}
},
computed: {
notLogin() {
return !this.isLogin
},
disabled() {
if (this.notLogin) return true
else if (this.cost > this.left) return true
else return false
},
bgColor() {
if (this.notLogin) return 'gray'
else if (this.cost > this.left) return 'gray'
else if (this.cost === this.left) return 'orange'
else return 'green'
}
},
data() {
return {
cost: 0,
left: 500,
isLogin: false
}
}
}
</script>
你可以发现 , 如果控制 button 的条件增加 , 我们也可以较为轻松的利用 computed
中的 disabled()
来算出是否需要 disabled
可是目前 WebComponent 中没有 Vue 阿 ! 我们要如何达到按钮的状态控制呢 ?
其实只要在变更资料时 , render 要生成的 html 可以很简单的达到状态控制欧 !
今天我们先说明到这 , 明天我们将实作 WebComponent 的状态控制
<<: 找LeetCode上简单的题目来撑过30天啦(DAY1)
>>: Line Bot 发送文字讯息外的格式 (Message types)
先读References: 很酷的网页: https://www.sinotrade.com.tw/...
参赛动机 刚好藉此机会了解开放银行及Open API的观念及应用方式,练习阅读分析API文件,最後尝...
目前MyButton有3个[Parameter],如果再增加的话,又要再定义新的[Parameter...
Q1. 常规文件是什麽? 网页专案中,有许多工程师惯用的文件命名方式,这些文件可能暗藏网页的相关资讯...
想看飞机又不想透过 FlightRadar24 !? 那就自己架一个接收站吧 ! 一、认识 ADS-...