day02
1. (掌握)JS中数组常用的响应式方法
- push()方法:在数组最后位置添加元素。可以添加多个元素
- pop() 方法:删除数组的最后一个元素
- shift()方法:删除数组的第一个元素
- unshift()方法:在数组最前面(第一个元素位置)添加元素.可以添加多个元素
- splice()方法:
- 删除元素、插入元素、替换元素
- sort()方法:对数组排序
- reverse()方法:数组元素进行反转.
<div id='app'>
<ul>
<li v-for='item in books'>{{item}}</li>
</ul>
<button @click="remove">
删除
</button>
</div>
<script>
new Vue({
el:'#app',
data:{
books:['java','c#','pythono']
},
methods:{
remove(){
this.books.splic(1,3);//第一个参数表示从什么位置开始
//第二个参数表示删除几个元素。如果是0 表示插入。插入的时候,后面要传入要插入的参数
this.books.splic(1,3,"a","b","c");//从1位置替换3个元素
this.books.splic(1,0,'m','n');//从1的位置插入m / n
this.books,splic(0,1,'cccc');//从0 的位置开始替换1个元素,替换的元素为 cccc
//使用vue的set方法来修改数组的元素.
Vue.set(this.books,0,'ccccc');
}
}
})
</script>
2. (练习)案例
需求:遍历数组的元素 ,第一个元素展示位红色。点击某个元素,颜色变成红色。
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<style>
.active{
color: red;
}
</style>
<body>
<div id="app">
<ul>
<li v-for="(item,index) in books"
:class="{active:currentIndex===index}"
@click="liChange(index)"
>
{{item}}
</li>
</ul>
<button @click="replace">替换元素</button>
</div>
<script>
new Vue({
el:'#app',
data:{
books:['a','b','c','d','e'],
currentIndex:0
},
methods:{
replace(){
//this.books.splice(0,0,'mm','nn')
this.books.reverse()
},
liChange(index){
this.currentIndex = index
}
}
})
</script>
</body>
3.(练习)购物车案例
- 保留两位小数: price.toFixed(2)
<button disabled>点击</button>
disabled 属性表示不能点击<button :disabled='item.count<=1'>点击</button>
小于等于1的时候不能点击.- 计算价格,使用computed计算属性来处理
<body>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<div id="app">
价格:{{price | priceFilter}}
<hr color="red"/>
<div v-if="this.bookInfo !=null">
<span v-for="(item,key,index) in bookInfo"
:key="item">
{{key}}:{{item}}<br/>
</span>
购买数量:
<button @click="subtraction"
:disabled="num===1">-</button>
[ {{num}} ]
<button @click="add">+</button>
<br/>
总价格:{{totalPrice}}
<br/> <a href="#" @click="remove">清空购物车</a>
</div>
<div v-else>
购物车里面没有商品
</div>
</div>
<script>
Vue.filter('priceFilter',function(value){
return '$'+value.toFixed(2);
});
const bookInfo={
name:'Java编程',
price:'39'
}
new Vue({
el:"#app",
data:{
price:22,
bookInfo,
num:1
},
methods:{
add(){
this.num++;
},
subtraction(){
this.num--;
},
remove(){
this.bookInfo = null;
}
},
computed:{
totalPrice(){
return this.num*this.bookInfo.price;
}
},
mounted() {
alert(this.bookInfo != null)
}
})
</script>
</body>
这里是模仿的一个案例,v-for遍历的是一个对象。
3.1 vue的过滤器filter
Vue中的过滤器分为全局过滤器和局部过滤器。
- 全局过滤器
<div id='app'>
价格:{{price | priceFileter}}
</div>
<script>
Vue.filter('priceFileter',function(value){
return '¥'+ value.toFixed(2)
});
new Vue({
el:'#app',
data:{
price:22
}
})
</script>
参考官网API文档:https://cn.vuejs.org/v2/guide/filters.html