前期准备:
一、完成页面布局,文件结构为css,data,img,js文件夹 ,address.html,cart.html文档
二、页面引入vue.js,和vue-resource.js文件,vue-resource.js不支持IE 9以下的浏览器
vue实践
一、创建vue实例,new Vue({}),实例中包括el,data,mounted(相当v1中的ready,但是在比较大型的项目中为保证文档全部准备完成,需加上 this.$nextTick(function(){...}))
二、获取商品数据,并输出到页面,用到知识点
1、获取数据通过vue-resource 方法 this.$http.get("数据来源(必须为绝对路径)").then(function(res){
}),获取数据中有一个坑需要注意,res.data才是真正需要的数据
2、获取到的数据存到一个data里面的变量里 productList
3、回到html页面绑定数据,用到v-for遍历,(item,index) in productList 通过json文件绑定需要的字段
4、输出金额格式,用到过滤器,filter,有全局过滤器和局部过滤器
filters: {
formatMoney: function(data) {
return "¥" + data.toFixed(2);
}
},
过滤器使用{{item.productPrice | formatMoney}}
5、选择商品数量
changeMoney: function(item, way) {
if (way > 0) {
item.productQuentity++
} else {
item.productQuentity--
if (item.productQuentity < 1) {
item.productQuentity = 1
}
}
this.getTotalMoney()
},
6、选择商品
selecetProdution: function(item) {
var _this = this;
if (typeof item.checked == "undefined") {
this.$set(item, "checked", true)//属性不存在,设置对象的属性。
//遍历是否全选
_this.productList.forEach(function(item, index) {
if (!item.checked) {
_this.checkAllFlag = false
} else {
_this.checkAllFlag = true
}
});
} else {
item.checked = !item.checked
_this.productList.forEach(function(item, index) {
if (!item.checked) {
_this.checkAllFlag = false
} else {
_this.checkAllFlag = true
}
});
}
this.getTotalMoney()
},
7、获取总金额
getTotalMoney: function() {
var _this = this;
_this.totalMoney = 0
_this.productList.forEach(function(item, index) {
if (item.checked) {
_this.totalMoney += item.productPrice * item.productQuentity
}
})
},
8、全选,取消全选功能
checkAll: function(flag) {
this.checkAllFlag = flag;
var _this = this;
_this.productList.forEach(function(item, index) {
if (typeof item.checked == "undefined") {
_this.$set(item, "checked", true)
} else {
item.checked = flag
}
})
this.getTotalMoney()
},