今天,我给大家带来的是利用vue.js来求总价的作业
在此之前,我们得明白一般我们是可以在模板内使用表达式的,但是建议只用于一些简单的运算,在执行一些复杂的运算逻辑时,一般不建议在模板中实现,这样会让模板过重难以维护。{{}}插值模板中不再是简单的数据绑定,而是包含了一些逻辑处理,一般在处理这些比较复杂的逻辑处理时,Vue.js框架提倡使用计算属性来处理,在计算属性当中,可以完成各种复杂的逻辑处理,包含运算逻辑、函数调用等等,只要最终返回一个结果即可。在Vue.js框架当中,所有计算属性都以函数的形式写在Vue实例的computed选项内,最终返回计算的结果。Vue.js中的事件处理方法可以根据用户的需要自定义,能通过单击事件、鼠标事件等触发,但是不能自动监听当前Vue实例对象的状态的变化。为了解决上述问题,Vue.js提供了watch状态监听功能,只要监听到当前Vue实例中数据的变化,就会调用当前数据所绑定的事件处理方法。
methods用来定义Vue实例中的方法,可以通过Vue实例直接访问这些方法。在定义的方法中,this对象指向Vue实例本身。通过methods定义的方法还可以作为页面中的事件处理方法使用,一旦事件被触发,即执行相应的方法进行处理。
在methods方法中访问 data 的数据,可以直接通过 this.属性名 的形式来访问,this表示Vue实例
所以,我们求总价的代码可以为
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<table border="1">
<thead>
<th>名称</th>
<th>出版日期</th>
<th>单价</th>
<th>数量</th>
<th>操作</th>
</thead>
<tr v-for="(item,index) in tableList" :key="index">
<td>{{item.title}}</td>
<td>{{item.dateTime}}</td>
<td>{{item.price}}</td>
<td>
<button type="button" @click="reduce(index)" :disabled="item.num==0">-</button>
{{item.num}}
<button type="button" @click="plus(index)">+</button>
</td>
<td><input type="button" value="移除"></td>
</tr>
<td>总价{{sum}}</td>
</table>
</div>
<script>
new Vue({
el:"#app",
data(){
return{
tableList: [
{
title: 'Bootstrap',
dateTime: '2021-01',
price: 50,
num: 1,
},
{
title: 'Vue.js开发实战',
dateTime: '2019-01',
price: 88,
num: 1
},
{
title: 'jQuery项目实战',
dateTime: '2021-01',
price: 45,
num: 1
},
{
title: 'java Web基础入门',
dateTime: '2021-01',
price: 45,
num: 1
},
]
}
},
methods:{
reduce(index){
this.tableList[
index
].num--;
},
plus(index){
this.tableList[
index
].num++
}
},
computed:{
sum(){
return this.tableList.reduce((total,item) =>{
return total+item.price*item.num
},0)
}
},
})
</script>
</body>
</html>
最终效果图为
在里面,我们可以自由更改数据,且数据大小不会小于0
这就是我的学习心得,谢谢大家