效果
代码
< template> < div id= "box" > < ! -- 全选功能-- > < input type= "checkbox" @change= "handleChange" v- model= "isAllChecked" / > < ! -- 绑定事件,不选用click,使用change每次check值改变会触发双向绑定布尔值-- > < ul> < li v- for = "data in datalist" > < input type= "checkbox" v- model= "checkgroup" : value= "data" @change= "handleLiChange" / > < ! -- v- model绑定数组,且要有value值value使用数组绑定 : value= "data.number||data.price||data.id||data.number*data.price" -- > { { data } } < ! -- 设置添加删除按钮-- > < button @click= "handleDelClick(data)" > del< / button> < ! -- 用户体验限制不小于0 所以不能使用data. number-- -- > { { data. number} } < ! -- 当前数量-- > < button @click= "data.number++" > add< / button> < ! -- data. number++ 自增1 点击事件,简单逻辑可直接使用代码-- > < / li> < / ul> { { checkgroup } } < p> 总金额计算: { { getSum ( ) } } < / p> < ! -- 函数表达式,函数要有返回值-- > < / div>
< / template>
< script lang= 'ts' >
import { reactive, toRefs, onBeforeMount, onMounted } from "vue" ;
import { useRouter, useRoute } from "vue-router" ;
export default { name : "" , setup ( ) { let router = useRouter ( ) , route = useRoute ( ) ; const data = reactive ( { checkgroup : [ ] , isAllChecked : false , datalist : [ { name : "商品1" , price : 10 , number : 1 , id : "1" , } , { name : "商品2" , price : 20 , number : 2 , id : "2" , } , { name : "商品3" , price : 30 , number : 3 , id : "3" , } , ] , getSum ( ) { var sum = 0 ; for ( var i in this . checkgroup) { sum += this . checkgroup[ i] . number * this . checkgroup[ i] . price; } return sum; } , handleChange ( ) { console. log ( "改变了" , this . isAllChecked) ; if ( this . isAllChecked) { this . checkgroup = this . datalist; } else { this . checkgroup = [ ] ; } } , handleLiChange ( ) { console. log ( "handleLiChange-判断是不是都勾选" ) ; if ( this . checkgroup. length === this . datalist. length) { this . isAllChecked = true ; } else { this . isAllChecked = false ; } } , handleDelClick ( data ) { data. number-- ; if ( data. number === 0 ) { data. number = 1 ; } } , } ) ; onBeforeMount ( ( ) => { } ) ; onMounted ( ( ) => { } ) ; const refData = toRefs ( data) ; return { ... refData, } ; } ,
} ;
< / script>
< style scoped> < / style>