案例一 折叠板
<template>
<div id="app">
<h3>案例:折叠面板</h3>
<div>
<div class="title">
<h4>芙蓉楼送辛渐</h4>
<span class="btn" @click='fn()'>
{{ isOK? '收起':'展开' }}
</span>
</div>
<div class="container" v-show='isOK'>
<p>寒雨连江夜入吴,</p>
<p>平明送客楚山孤。</p>
<p>洛阳亲友如相问,</p>
<p>一片冰心在玉壶。</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isOK:false
}
},
methods:{
fn(){
this.isOK=!this.isOK
}
}
}
</script>
<style>
body {
background-color: #ccc;
}
#app {
width: 400px;
margin: 20px auto;
background-color: #fff;
border: 4px solid blueviolet;
border-radius: 1em;
box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.5);
padding: 1em 2em 2em;
}
h3 {
text-align: center;
}
.title {
display: flex;
justify-content: space-between;
align-items: center;
border: 1px solid #ccc;
padding: 0 1em;
}
.title h4 {
line-height: 2;
margin: 0;
}
.container {
border: 1px solid #ccc;
padding: 0 1em;
}
.btn {
/* 鼠标改成手的形状 */
cursor: pointer;
}
</style>
案例二 点击生成按钮随机生成数字,点击删除按钮可以删除随机数字
<div>
<ul>
<li v-for="(el,index) in arr" :key='index'>{{el}}<button @click="fn2(index)">删除</button></li>
</ul>
<button @click='fn()'>生成</button>
</div>
</template>
<script>
export default {
data(){
return {
arr:[1,2,3]
}
},
methods:{
fn(){
//生成随机数
let mun= Math.floor( Math.random()*20)
//添加到arr
this.arr.push(mun)
},
fn2(index){
//通过传参拿到数组的下标,删除指定下标的元素
this.arr.splice(index,1)
}
}
}
</script>
<style>
</style>
案例3 购物车
<template>
<div id="app">
<table class="tb">
<tr>
<th>编号</th>
<th>品牌名称</th>
<th>创立时间</th>
<th>操作</th>
</tr>
<!-- 循环渲染的元素tr -->
<tr v-for="(el,index) in list" :key="index">
<td>{{el.id}}</td>
<td>{{el.name}}</td>
<td>{{el.time}}</td>
<td>
<button @click="fn(index)">删除</button>
</td>
</tr>
<!-- 判断数组中第一个元素是否存在会返回一个布尔值,直接赋值给v-show -->
<tr v-show="!list[0]">
<td colspan="4" >没有数据咯~</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: "奔驰", time: "2020-08-01" },
{ id: 2, name: "宝马", time: "2020-08-02" },
{ id: 3, name: "奥迪", time: "2020-08-03" },
],
};
},
methods:{
fn(index){
//通过传参拿到数组的下标
this.list.splice(this.list[index],1)
}
}
};
</script>
<style>
#app {
width: 600px;
margin: 10px auto;
}
.tb {
border-collapse: collapse;
width: 100%;
}
.tb th {
background-color: #0094ff;
color: white;
}
.tb td,
.tb th {
padding: 5px;
border: 1px solid black;
text-align: center;
}
.add {
padding: 5px;
border: 1px solid black;
margin-bottom: 10px;
}
</style>
案例4
<template>
<div>
<ul>
<li v-for='(el,index) in arr' :key='index' >{{el}},{{index}}</li>
</ul>
<button @click="fn()">走一走</button>
</div>
</template>
<script>
export default {
data(){
return{
arr:['帅哥','美女','程序员']
}
},
methods:{
fn(){
//先往数组添加第一个元素
this.arr.push(this.arr[0])
//载删除最后一个元素
this.arr.shift(this.arr[0])
}
}
}
</script>
<style>
</style>