01-组件-4步曲
案例用less写的样式, 所以下载
yarn add less less-loader@5.0.0 -D
模板标签
<template>
<div id="app">
<h3>案例:折叠面板</h3>
<div>
<div class="title">
<h4>芙蓉楼送辛渐</h4>
<span class="btn" @click="isShow = !isShow">
{{ isShow ? '收起' : '展开' }}
</span>
</div>
<div class="container" v-show="isShow">
<p>寒雨连江夜入吴, </p>
<p>平明送客楚山孤。</p>
<p>洛阳亲友如相问,</p>
<p>一片冰心在玉壶。</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isShow: false
}
}
}
</script>
<style lang="less">
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>
在componnents里新建Panel
/目标: 如何创建和使用组件
1. 创建组件 -> 封装标签, 样式, js -> vue实例(脚手架环境, 我们采用.vue文件形式)
2. 引入组件
import Panel from "./components/Panel";
3. 注册组件 - 方法1(全局注册)
// 语法: Vue.component('组件名', 组件对象)
3. 注册组件 - 方式2(局部注册)
// 组件名: 组件对象
Panel.vue
<template>
<div>
<div class="title">
<h4>芙蓉楼送辛渐</h4>
<span class="btn" @click="isShow = !isShow">
{{ isShow ? "收起" : "展开" }}
</span>
</div>
<div class="container" v-show="isShow">
<p>寒雨连江夜入吴,</p>
<p>平明送客楚山孤。</p>
<p>洛阳亲友如相问,</p>
<p>一片冰心在玉壶。</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isShow: false,
};
},
}
</script>
<style scoped>
.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>
App.vue
<template>
<div id="app">
<h3>案例:折叠面板</h3>
<Pannel></Pannel>
<Pannel></Pannel>
<Pannel></Pannel>
</div>
</template>
<script>
// 目标: 如何创建和使用组件
// 1. 创建组件 -> 封装标签, 样式, js -> vue实例(脚手架环境, 我们采用.vue文件形式)
// 2. 引入组件
import Panel from "./components/Panel";
// 3. 注册组件 - 方法1(全局注册)
// 语法: Vue.component('组件名', 组件对象)
// import Vue from 'vue'
// Vue.commponent('Pannel', Panel)
export default {
// 3. 注册组件 - 方式2(局部注册)
components: {
// 组件名: 组件对象
Pannel: Panel,
// Panel: Panel
// 组件名(key) 和 组件对象(value) 名字相同简写
// Panel
},
};
</script>
<style lang="less" scoped>
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;
}
}
}
</style>
图片显示
02-组件通信-父向子的基础使用
在componnents里新建MyProduct
App.vue
<template>
<div>
<MyProduct title="超级好吃的口水鸡" price="50" intro="开业大酬宾, 全场8折"></MyProduct>
<MyProduct title="超级好吃的铁锅炖" price="300" intro="正宗的东北铁锅炖,嘎嘎好吃"></MyProduct>
<MyProduct title="超级好吃的蛙锅" price="500" intro="好吃的停不下来,都来尝一尝吧"></MyProduct>
</div>
</template>
<script>
// 目标: 组件通信
// 场景(口诀): 从某.vue文件, 向另外.vue文件 传值
// 使用:
// 方法1: 父 -> 子(传值)
// 被引入的是儿子
// 语法:
// (1): 子组件内, props:[变量1, 变量2]
// (2): 父组件内, 在使用组件标签时, 向变量传值
import MyProduct from "./components/MyProduct";
export default {
components: {
MyProduct,
},
};
</script>
<style>
</style>
MyProduct.vue
<template>
<div class="my-product">
<h3>标题: {{ title }}</h3>
<p>价格: {{ price }}</p>
<p>{{ intro }}</p>
</div>
</template>
<script>
export default {
// (1): 子组件内定义变量
// vue会把他们解析成变量的
props: ["title", "price", "intro"],
};
</script>
<style>
.my-product {
width: 400px;
padding: 20px;
border: 2px solid #000;
border-radius: 5px;
margin: 10px;
}
</style>
组件通信-父向子-配合循环
App.vue
<template>
<div>
<MyProduct
v-for="obj in list"
:key="obj.id"
:title="obj.proname"
:price="obj.proprice"
:intro="obj.info"
></MyProduct>
</div>
</template>
<script>
// 目标: 组件配合循环使用
// v-for 每次循环是独立, 组件每创建一次独立
// 组件一般就用于展示数据的
import MyProduct from "./components/MyProduct";
export default {
data() {
return {
list: [
{
id: 1,
proname: "超级好吃的棒棒糖",
proprice: 18.8,
info: "开业大酬宾, 全场8折",
},
{
id: 2,
proname: "超级好吃的大鸡腿",
proprice: 34.2,
info: "好吃不腻, 快来买啊",
},
{
id: 3,
proname: "超级无敌的冰激凌",
proprice: 14.2,
info: "炎热的夏天, 来个冰激凌了",
},
],
};
},
components: {
MyProduct,
},
};
</script>
<style>
</style>
MyProduct.vue
<template>
<div class="my-product">
<h3>标题: {{ title }}</h3>
<p>价格: {{ price }}</p>
<p>{{ intro }}</p>
</div>
</template>
<script>
export default {
// (1): 子组件内定义变量
// vue会把他们解析成变量的
props: ["title", "price", "intro"],
};
</script>
<style>
.my-product {
width: 400px;
padding: 20px;
border: 2px solid #000;
border-radius: 5px;
margin: 10px;
}
</style>
组件通信-子向父
在componnents里新建MyProduct_Sub
App.vue
<template>
<div>
<MyProduct
v-for="(obj, ind) in list"
:key="obj.id"
:title="obj.proname"
:price="obj.proprice"
:intro="obj.info"
:index="ind"
@subPrice="fn"
></MyProduct>
</div>
</template>
<script>
import MyProduct from "./components/MyProduct_Sub";
export default {
data() {
return {
list: [
{
id: 1,
proname: "超级好吃的棒棒糖",
proprice: 18.8,
info: "开业大酬宾, 全场8折",
},
{
id: 2,
proname: "超级好吃的大鸡腿",
proprice: 34.2,
info: "好吃不腻, 快来买啊",
},
{
id: 3,
proname: "超级无敌的冰激凌",
proprice: 14.2,
info: "炎热的夏天, 来个冰激凌了",
},
],
};
},
methods: {
fn(ind, price) {
// 数据源list里砍价
let obj = this.list[ind];
if (obj.proprice > 1) {
// obj.proprice = (obj.proprice - price).toFixed(2)
obj.proprice -= price;
}
},
},
components: {
MyProduct,
},
};
</script>
<style>
</style>
MyProduct_Sub
<template>
<div class="my-product">
<h3>标题: {{ title }}</h3>
<p>价格: {{ price }}</p>
<p>{{ intro }}</p>
<button @click="kanFn">砍一刀</button>
</div>
</template>
<script>
// 目标: 砍一刀
// 结论: props的变量(只读的)
// 原因: 修改props变量值的时候,出现红色警告
// 我在子组件改props值也没用, 父组件重新渲染会把props的值覆盖
// 目标: 子向父传值
// 语法:
// (1): 父组件内, 给子组件标签 - 绑定自定事件
// @自定义事件名="父methods里函数名"
// (2): 子组件内, "恰当的时机"
// this.$emit('自定义事件名', 值)
// 效果: 触发此标签身上的对应事件名
export default {
// (1): 子组件内定义变量
// vue会把他们解析成变量的
props: ["title", "price", "intro", "index"],
methods: {
kanFn() {
// 把索引和砍得价格传给父组件
this.$emit("subPrice", this.index, Math.random());
},
},
};
</script>
<style>
.my-product {
width: 400px;
padding: 20px;
border: 2px solid #000;
border-radius: 5px;
margin: 10px;
}
</style>
画图显示
todo案例
1.todo案例-创建工程和组件
vue create todo-list // 建工程
根据需求定义3个组件准备复用
components/TodoHeader.vue - 复制标签和类名
<template>
<header class="header">
<h1>todos</h1>
<input id="toggle-all" class="toggle-all" type="checkbox" >
<label for="toggle-all"></label>
<input
class="new-todo"
placeholder="输入任务名称-回车确认"
autofocus
/>
</header>
</template>
<script>
export default {
}
</script>
components/TodoMain.vue - 复制标签和类名
<template>
<ul class="todo-list">
<!-- completed: 完成的类名 -->
<li class="completed" >
<div class="view">
<input class="toggle" type="checkbox" />
<label>任务名</label>
<button class="destroy"></button>
</div>
</li>
</ul>
</template>
<script>
export default {
}
</script>
components/TodoFooter.vue - 复制标签和类名
<template>
<footer class="footer">
<span class="todo-count">剩余<strong>数量值</strong></span>
<ul class="filters">
<li>
<a class="selected" href="javascript:;" >全部</a>
</li>
<li>
<a href="javascript:;">未完成</a>
</li>
<li>
<a href="javascript:;" >已完成</a>
</li>
</ul>
<button class="clear-completed" >清除已完成</button>
</footer>
</template>
<script>
export default {
}
</script>
App.vue中引入和使用
<template>
<section class="todoapp">
<!-- 除了驼峰, 还可以使用-转换链接 -->
<TodoHeader></TodoHeader>
<TodoMain></TodoMain>
<TodoFooter></TodoFooter>
</section>
</template>
<script>
// 1.0 样式引入
import "./styles/base.css"
import "./styles/index.css"
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
export default {
components: {
TodoHeader,
TodoMain,
TodoFooter,
},
};
</script>
样式src/styles/bass.css
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #c5c5c5;
border-bottom: 1px dashed #f7f7f7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
#issue-count {
display: none;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
.learn-bar > .learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
transition-property: left;
transition-duration: 500ms;
}
@media (min-width: 899px) {
.learn-bar {
width: auto;
padding-left: 300px;
}
.learn-bar > .learn {
left: 8px;
}
}
样式src/styles/index.css
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
font-weight: inherit;
color: inherit;
-webkit-appearance: none;
appearance: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #f5f5f5;
color: #111111;
min-width: 230px;
max-width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 300;
}
:focus {
outline: 0;
}
.hidden {
display: none;
}
.todoapp {
background: #fff;
margin: 130px 0 40px 0;
position: relative;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.todoapp input::-webkit-input-placeholder {
font-style: italic;
font-weight: 300;
color: rgba(0, 0, 0, 0.4);
}
.todoapp input::-moz-placeholder {
font-style: italic;
font-weight: 300;
color: rgba(0, 0, 0, 0.4);
}
.todoapp input::input-placeholder {
font-style: italic;
font-weight: 300;
color: rgba(0, 0, 0, 0.4);
}
.todoapp h1 {
position: absolute;
top: -140px;
width: 100%;
font-size: 80px;
font-weight: 200;
text-align: center;
color: #b83f45;
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
.new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
font-weight: inherit;
line-height: 1.4em;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.003);
box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
}
.main {
position: relative;
z-index: 2;
border-top: 1px solid #e6e6e6;
}
.toggle-all {
width: 1px;
height: 1px;
border: none; /* Mobile Safari */
opacity: 0;
position: absolute;
right: 100%;
bottom: 100%;
}
.toggle-all + label {
width: 60px;
height: 34px;
font-size: 0;
position: absolute;
top: 12px;
left: -13px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
z-index: 9999
}
.toggle-all + label:before {
content: '❯';
font-size: 22px;
color: #e6e6e6;
padding: 10px 27px 10px 27px;
}
.toggle-all:checked + label:before {
color: #737373;
}
.todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px solid #ededed;
}
.todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
display: block;
width: calc(100% - 43px);
padding: 12px 16px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
appearance: none;
}
.todo-list li .toggle {
opacity: 0;
}
.todo-list li .toggle + label {
/*
Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433
IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/
*/
background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E');
background-repeat: no-repeat;
background-position: center left;
}
.todo-list li .toggle:checked + label {
background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E');
}
.todo-list li label {
word-break: break-all;
padding: 15px 15px 15px 60px;
display: block;
line-height: 1.2;
transition: color 0.4s;
font-weight: 400;
color: #4d4d4d;
}
.todo-list li.completed label {
color: #cdcdcd;
text-decoration: line-through;
}
.todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 30px;
color: #cc9a9a;
margin-bottom: 11px;
transition: color 0.2s ease-out;
}
.todo-list li .destroy:hover {
color: #af5b5e;
}
.todo-list li .destroy:after {
content: '×';
}
.todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
padding: 10px 15px;
height: 20px;
text-align: center;
font-size: 15px;
border-top: 1px solid #e6e6e6;
}
.footer:before {
content: '';
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 50px;
overflow: hidden;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
0 8px 0 -3px #f6f6f6,
0 9px 1px -3px rgba(0, 0, 0, 0.2),
0 16px 0 -6px #f6f6f6,
0 17px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
float: left;
text-align: left;
}
.todo-count strong {
font-weight: 300;
}
.filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
.filters li {
display: inline;
}
.filters li a {
color: inherit;
margin: 3px;
padding: 3px 7px;
text-decoration: none;
border: 1px solid transparent;
border-radius: 3px;
}
.filters li a:hover {
border-color: rgba(175, 47, 47, 0.1);
}
.filters li a.selected {
border-color: rgba(175, 47, 47, 0.2);
}
.clear-completed,
html .clear-completed:active {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
cursor: pointer;
}
.clear-completed:hover {
text-decoration: underline;
}
.info {
margin: 65px auto 0;
color: #4d4d4d;
font-size: 11px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
text-align: center;
}
.info p {
line-height: 1;
}
.info a {
color: inherit;
text-decoration: none;
font-weight: 400;
}
.info a:hover {
text-decoration: underline;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
.toggle-all,
.todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
height: 40px;
}
}
@media (max-width: 430px) {
.footer {
height: 50px;
}
.filters {
bottom: 10px;
}
}
2.todo案例-铺设待办任务
App.vue
<TodoMain :arr="showArr"></TodoMain>
export default {
data() {
return {
list: [
{ id: 100, name: "吃饭", isDone: true },
{ id: 201, name: "睡觉", isDone: false },
{ id: 103, name: "打豆豆", isDone: true },
],
};
}
};
TodoMain.vue
<template>
<ul class="todo-list">
<!-- 2.2 循环任务-关联选中状态-铺设数据 -->
<!-- completed: 完成的类名 -->
<li :class="{completed: obj.isDone}" v-for="(obj, index) in arr" :key='obj.id'>
<div class="view">
<input class="toggle" type="checkbox" v-model="obj.isDone"/>
<label>{{ obj.name }}</label>
<!-- 4.0 注册点击事件 -->
<button @click="delFn(index)" class="destroy"></button>
</div>
</li>
</ul>
</template>
<script>
export default {
props: ["list"]
};
</script>
<style>
</style>
3.todo案例-添加任务
TodoHeader.vue
<template>
<header class="header">
<h1>todos</h1>
<input id="toggle-all" class="toggle-all" type="checkbox" v-model="isAll">
<label for="toggle-all"></label>
<!-- 3.0 键盘事件-回车按键
3.1 输入框 - v-model获取值
-->
<input
class="new-todo"
placeholder="输入任务名称-回车确认"
autofocus
@keydown.enter="downFn"
v-model="task"
/>
</header>
</template>
<script>
// 3. 目标 - 新增任务
export default {
data(){
return {
task: ""
}
},
methods: {
downFn(){
if (this.task.trim().length === 0) {
alert("任务名不能为空");
return;
}
// 3.2(重要) - 当前任务名字要加到list数组里
// 子传父技术
this.$emit("create", this.task)
this.task = ""
}
}
}
</script>
App.vue
<TodoHeader @create="createFn"></TodoHeader>
methods: {
createFn(taskName){ // 添加任务
// 3.3 push到数组里
let id = this.list.length == 0 ? 100 : this.list[this.list.length - 1].id + 1
this.list.push({
id: id,
name: taskName,
isDone: false
})
},
}
4.todo案例-删除任务
App.vue - 传入自定义事件等待接收要被删除的序号
<TodoMain :arr="showArr" @del="deleteFn"></TodoMain>
methods: {
deleteFn(theId){ // 删除任务
let index = this.list.findIndex(obj => obj.id === theId)
this.list.splice(index, 1)
},
},
TodoMain.vue - 把id传回去实现删除(想好数据在哪里, 就在哪里删除)
<!-- 4.0 注册点击事件 -->
<button class="destroy" @click="delFn(obj.id)"></button>
methods: {
delFn(id){
// 4.1 子传父
this.$emit('del', id)
}
}
5.todo案例-底部统计
TodoFooter.vue - 接收list统计直接显示
<template>
<footer class="footer">
<span class="todo-count">剩余<strong>{{ count }}</strong></span>
<ul class="filters">
<li>
<a class="selected" href="javascript:;">全部</a>
</li>
<li>
<a href="javascript:;">未完成</a>
</li>
<li>
<a href="javascript:;">已完成</a>
</li>
</ul>
<button class="clear-completed">清除已完成</button>
</footer>
</template>
<script>
export default {
// 5.0 props定义
props: ['farr'],
// 5.1 计算属性 - 任务数量
computed: {
count(){
return this.farr.length
}
},
}
</script>
<style>
</style>
App.vue - 传入数据
<TodoFooter :farr="showArr"></TodoFooter>
6.todo案例-数据切换
App.vue
<TodoFooter :farr="showArr" @changeType="typeFn"></TodoFooter>
<script>
export default{
data(){
return {
// ...其他省略
getSel: "all" // 默认显示全部
}
},
methods: {
// ...其他省略
typeFn(str){ // 'all' 'yes' 'no' // 修改类型
this.getSel = str
},
},
// 6.5 定义showArr数组 - 通过list配合条件筛选而来
computed: {
showArr(){
if (this.getSel === 'yes') { // 显示已完成
return this.list.filter(obj => obj.isDone === true)
} else if (this.getSel === 'no') { // 显示未完成
return this.list.filter(obj => obj.isDone === false)
} else {
return this.list // 全部显示
}
}
},
}
</script>
TodoFooter.vue
<template>
<footer class="footer">
<span class="todo-count">剩余<strong>{{ count }}</strong></span>
<ul class="filters" @click="fn">
<li>
<!-- 6.1 判断谁应该有高亮样式: 动态class
6.2 用户点击要切换isSel里保存的值
-->
<a :class="{selected: isSel === 'all'}" href="javascript:;" @click="isSel='all'">全部</a>
</li>
<li>
<a :class="{selected: isSel === 'no'}" href="javascript:;" @click="isSel='no'">未完成</a>
</li>
<li>
<a :class="{selected: isSel === 'yes'}" href="javascript:;" @click="isSel='yes'">已完成</a>
</li>
</ul>
<!-- 7. 目标: 清除已完成 -->
<!-- 7.0 点击事件 -->
<button class="clear-completed" >清除已完成</button>
</footer>
</template>
<script>
// 5. 目标: 数量统计
export default {
// 5.0 props定义
props: ['farr'],
// 5.1 计算属性 - 任务数量
computed: {
count(){
return this.farr.length
}
},
// 6. 目标: 点谁谁亮
// 6.0 变量isSel
data(){
return {
isSel: 'all' // 全部:'all', 已完成'yes', 未完成'no'
}
},
methods: {
fn(){ // 切换筛选条件
// 6.3 子 -> 父 把类型字符串传给App.vue
this.$emit("changeType", this.isSel)
}
}
}
</script>
7.todo案例-清空已完成
App.vue - 先传入一个自定义事件-因为得接收TodoFooter.vue里的点击事件
<TodoFooter :farr="showArr" @changeType="typeFn" @clear="clearFun"></TodoFooter>
<script>
methods: {
// ...省略其他
clearFun(){ // 清除已完成
this.list = this.list.filter(obj => obj.isDone == false)
}
}
</script>
TodoFooter.vue
<!-- 7. 目标: 清除已完成 -->
<!-- 7.0 点击事件 -->
<button class="clear-completed" @click="clearFn">清除已完成</button>
<script>
methods: {
clearFn(){ // 清空已完成任务
// 7.1 触发App.vue里事件对应clearFun方法
this.$emit('clear')
}
}
</script>
8.todo案例-数据缓存
App.vue
<script>
export default {
data(){
return {
// 8.1 默认从本地取值
list: JSON.parse(localStorage.getItem('todoList')) || [],
// 6.4 先中转接收类型字符串
getSel: "all" // 默认显示全部
}
},
// 8. 目标: 数据缓存
watch: {
list: {
deep: true,
handler(){
// 8.0 只要list变化 - 覆盖式保存到localStorage里
localStorage.setItem('todoList', JSON.stringify(this.list))
}
}
}
};
</script>
9.todo案例-全选功能
TodoHeader.vue
<!-- 9. 目标: 全选状态
9.0 v-model关联全选状态
页面变化(勾选true, 未勾选false) -> v-model -> isAll变量
-->
<input id="toggle-all" class="toggle-all" type="checkbox" v-model="isAll">
<script>
export default {
// ...其他省略
// 9.1 定义计算属性
computed: {
isAll: {
set(checked){ // 只有true / false
// 9.3 影响数组里每个小选框绑定的isDone属性
this.arr.forEach(obj => obj.isDone = checked)
},
get(){
// 9.4 小选框统计状态 -> 全选框
// 9.5 如果没有数据, 直接返回false-不要让全选勾选状态
return this.arr.length !== 0 && this.arr.every(obj => obj.isDone === true)
}
}
},
}
</script>
App.vue
<TodoHeader :arr="showArr" @create="createFn"></TodoHeader>
10.todo案例全面加注释
App.vue
<template>
<div>
<div class="todoapp">
<TodoHeader
:arr="showArr"
@addEvent="addFn"
@complateEvent="complateFn"
></TodoHeader>
<TodoMain :arr="showArr" @delEvent="delFn"></TodoMain>
<TodoFooter
:arr="showArr"
@changeEvent="changeFn"
@clearEvent="clearFn"
></TodoFooter>
</div>
</div>
</template>
<script>
// 需求1: 创建todo-list工程-准备3个组件-铺设
// 1.0 创建3个组件文件, 把styles文件复制过来, 组件标签准备好
// 1.1 引入App.vue-主入口页面上使用
import "./styles/base.css";
import "./styles/index.css";
// 1.2 引入组测使用
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
// 1.3 注册组件
// 1.4.使用组件
// 需求2: 铺设代办任务
// 2.0 准备数据list数组
// 2.1 数组 -> TodoMain.vue里面(列表当作了Todomain)
// 2.2 TodoMain.vue里, v-for循环接收到数组
// 2.3 v-model关联isDone属性和复选框
// 2.4 设置完成样式类名
// 需求3: 新增任务
// 思想: 某个数组逻辑-就在数组定义页面做(统一)
// 3.0 TodoHeader.vue中, 输入框- 回车事件
// 3.1 v-model关联输入框, 拿到任务名
// 3.2 要加入到list数组里, 发现list在App.vue里, 子传父技术(上口诀)
// 3.3 产生id,和对象加入到list数组里
// 3.4 防止用户输入空内容, 完成后清空输入框
// 需求4: 删除任务
// 4.0 删除按钮 - 点击事件 - 传入任务id
// 4.1 TodoMain.vue => 要删除任务id => App.vue(子向父技术)
// 4.2 父组件方法, 通过id找到下标, 删除list数组元素
// 核心: list数据源, 增/删/改/查, 所有用到list的地方都会更新(vue响应式的数据驱动页面)
// 需求5: 底部数量统计
// 5.0 App.vue 里list数组 -> TodoFooter.vue里(父 -> 子传值)
// 5.1 子组件内, 数组.length 显示数据数量
// 需求6: 数据筛选
// 先实现高亮
// 6.0 绑定点击事件-一个事件方法
// 6.1 需要区分高亮的类名, 用经验, 一个变量保存该高亮的类名, 然后和自己的标记做判断,相等就高亮class
// 筛选选择功能
// 6.2 TodoFoote把标记字符传给App.vue(子->父)
// 6.3(难): 不能再传递list数组给TodoMain, 重新定义showArr计算属性(数组), list和标记判断筛选出来的数据结果
// 6.4 把showArr传给TodoMain和TodoFooter
// 需求7: 清除已完成
// 7.0 清除按钮 - 点击事件
// 7.1 子传父App.vue - 自定义事件
// 7.2 App.vue里clearFn中, 实现过滤未完成覆盖给list数组
// 需求8:数据缓存
// 8.0 watch深度侦听list数组变化, 只要变化, 就把当前list数组+对象值, 覆盖到本地todoList上存
// 8.1 list 变量默认值, 从本地提取
// 需求9: 全选
// 9.0 - 全选框 v-model绑定isAll计算属性
// 9.1 - 统计小选框影响全选框, 使用every方法统计
// 9.2 - 页面全选框改变, 选中状态 -> 改写isAll计算属性完成写法
// 9.3 - 在set里拿到选中状态 -> App.vue, 影响小选框obj.isDone值
export default {
data() {
return {
list: JSON.parse(localStorage.getItem("todoList")) || [],
isStr: "all", // 标记现在筛选状态
};
},
computed: {
showArr() {
// 标记和list原数组, 筛选
if (this.isStr === "yes") {
// 已完成数组
// filter过滤
return this.list.filter((obj) => obj.isDone === true);
} else if (this.isStr === "no") {
return this.list.filter((obj) => obj.isDone === false);
} else {
return this.list;
}
},
},
methods: {
addFn(todoName) {
let theId =
this.list.length === 0 ? 100 : this.list[this.list.length - 1].id + 1;
this.list.push({
id: theId,
name: todoName,
isDone: false,
});
},
delFn(id) {
let index = this.list.findIndex((obj) => obj.id === id);
this.list.splice(index, 1);
},
// 改变筛选数据标记
changeFn(str) {
this.isStr = str;
},
// 清空已完成任务的方法
clearFn() {
// 思路: 把未完成筛选出来, 覆盖给list数组
this.list = this.list.filter((obj) => obj.isDone === false);
},
complateFn(bool) {
this.list.forEach((obj) => {
obj.isDone = bool;
});
},
},
watch: {
list: {
deep: true,
handler() {
localStorage.setItem("todoList", JSON.stringify(this.list));
},
},
},
components: {
TodoHeader,
TodoMain,
TodoFooter,
},
};
</script>
components/TodoHeader.vue
<template>
<header class="header">
<h1>todos</h1>
<input id="toggle-all" class="toggle-all" type="checkbox" v-model="isAll" />
<label for="toggle-all"></label>
<input
class="new-todo"
placeholder="输入任务名称-回车确认"
autofocus
@keyup.enter="enterFn"
v-model="todoName"
/>
</header>
</template>
<script>
export default {
data() {
return {
todoName: "", // 任务名
};
},
methods: {
enterFn() {
if (this.todoName.trim().length === 0) {
return alert("请输入任务名");
}
this.$emit("addEvent", this.todoName);
this.todoName = "";
},
},
props: ["arr"],
computed: {
isAll: {
set(val) {
this.$emit("complateEvent", val);
},
get() {
return this.arr.every((obj) => obj.isDone === true);
},
},
},
};
</script>
components/TodoMain.vue
<template>
<ul class="todo-list">
<!-- completed: 完成的类名 -->
<li v-for="obj in arr" :key="obj.id" :class="{ completed: obj.isDone }">
<div class="view">
<input class="toggle" type="checkbox" v-model="obj.isDone" />
<label>{{ obj.name }}</label>
<button class="destroy" @click="delFn(obj.id)"></button>
</div>
</li>
</ul>
</template>
<script>
export default {
props: ["arr"],
methods: {
delFn(theId) {
this.$emit("delEvent", theId);
},
},
};
</script>
components/TodoFooter.vue
<template>
<footer class="footer">
<span class="todo-count"
>剩余<strong>{{ arr.length }}</strong></span
>
<ul class="filters">
<li>
<a
:class="{ selected: isH === 'all' }"
href="javascript:;"
@click="changeFn('all')"
>全部</a
>
</li>
<li>
<a
:class="{ selected: isH === 'no' }"
href="javascript:;"
@click="changeFn('no')"
>未完成</a
>
</li>
<li>
<a
:class="{ selected: isH === 'yes' }"
href="javascript:;"
@click="changeFn('yes')"
>已完成</a
>
</li>
</ul>
<button class="clear-completed" @click="clearFn">清除已完成</button>
</footer>
</template>
<script>
// 经验: 点击高亮的需求
// 一个变量保存当前应该高亮的标记(下标,'字母','单词','数字')
// 分别判断(高亮值 -> 本应该对应的值 === 判断)
export default {
data() {
return {
isH: "all",
};
},
methods: {
changeFn(theStr) {
this.isH = theStr;
this.$emit("changeEvent", theStr);
},
// 清空已完成
clearFn(){
this.$emit("clearEvent")
}
},
props: ["arr"],
};
</script>
作业案例
1.喜欢小狗狗吗
先建设装备 vue create todo-list
App.vue
<template>
<div>
<Dog></Dog>
<Dog/>
</div>
</template>
<script>
import Dog from './components/Dog'
export default {
components: {
Dog
}
}
</script>
<style>
</style>
./components/Dog
<template>
<div class="my_dog">
<img
src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg3.doubanio.com%2Fview%2Fgroup_topic%2Fl%2Fpublic%2Fp143410681.jpg&refer=http%3A%2F%2Fimg3.doubanio.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635249660&t=d14debc18e80a076967bdf9b6d09533a"
alt=""
/>
<p>这是一个孤独可怜的狗</p>
</div>
</template>
<script>
export default {};
</script>
<style>
.my_dog {
width: 400px;
border: 1px solid black;
text-align: center;
float: left;
}
.my_dog img {
width: 100%;
height: 300px;
}
</style>
效果图
2.点击文字变色
App.vue
<template>
<div>
<Dog></Dog>
<Dog />
</div>
</template>
<script>
import Dog from "./components/Dog2";
export default {
components: {
Dog,
},
};
</script>
<style>
</style>
./components/Dog2.vue
<template>
<div class="my_dog">
<img
src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg3.doubanio.com%2Fview%2Fgroup_topic%2Fl%2Fpublic%2Fp143410681.jpg&refer=http%3A%2F%2Fimg3.doubanio.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635249660&t=d14debc18e80a076967bdf9b6d09533a"
alt=""
/>
<!-- 点击事件 -->
<p :style="{ backgroundColor: colorStr }" @click="btn">
这是一个孤独可怜的狗
</p>
</div>
</template>
<script>
export default {
data() {
return {
colorStr: "",
};
},
methods: {
btn() {
this.colorStr = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(
Math.random() * 256
)}, ${Math.floor(Math.random() * 256)})`;
},
},
};
</script>
<style>
.my_dog {
width: 300px;
border: 1px solid black;
text-align: center;
float: left;
}
.my_dog img {
width: 100%;
height: 200px;
}
</style>
效果图
3.卖狗啦
App.vue
<template>
<div>
<Dog
v-for="(obj, index) in arr"
:key="index"
:imgurl="obj.dogImgUrl"
:dogname="obj.dogName"
></Dog>
</div>
</template>
<script>
import Dog from "./components/Dog3";
export default {
data() {
return {
// 1. 准备数据
arr: [
{
dogImgUrl:
"http://nwzimg.wezhan.cn/contents/sitefiles2029/10146688/images/21129958.jpg",
dogName: "博美",
},
{
dogImgUrl:
"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1224576619,1307855467&fm=26&gp=0.jpg",
dogName: "泰迪",
},
{
dogImgUrl:
"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2967740259,1518632757&fm=26&gp=0.jpg",
dogName: "金毛",
},
{
dogImgUrl:
"https://pic1.zhimg.com/80/v2-7ba4342e6fedb9c5f3726eb0888867da_1440w.jpg?source=1940ef5c",
dogName: "哈士奇",
},
{
dogImgUrl:
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1563813435580&di=946902d419c3643e33a0c9113fc8d780&imgtype=0&src=http%3A%2F%2Fvpic.video.qq.com%2F3388556%2Fd0522aynh3x_ori_3.jpg",
dogName: "阿拉斯加",
},
{
dogImgUrl:
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1563813454815&di=ecdd2ebf479568453d704dffacdfa12c&imgtype=0&src=http%3A%2F%2Fwww.officedoyen.com%2Fuploads%2Fallimg%2F150408%2F1-15040Q10J5B0.jpg",
dogName: "萨摩耶",
},
],
};
},
components: {
Dog,
},
};
</script>
./components/Dog3
<template>
<div class="my_dog">
<img :src="imgurl" alt="" />
<p :style="{ backgroundColor: colorStr }" @click="btn">{{ dogname }}</p>
</div>
</template>
<script>
export default {
props: ["imgurl", "dogname"],
data() {
return {
colorStr: "",
};
},
methods: {
btn() {
this.colorStr = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(
Math.random() * 256
)}, ${Math.floor(Math.random() * 256)})`;
},
},
};
</script>
<style scoped>
.my_dog {
width: 300px;
border: 1px solid black;
text-align: center;
float: left;
}
.my_dog img {
width: 100%;
height: 300px;
}
</style>
图
4.选择喜欢的狗
App.vue
<template>
<div>
<Dog
v-for="(obj, index) in arr"
:key="index"
:imgurl="obj.dogImgUrl"
:dogname="obj.dogName"
@love="fn"
></Dog>
<hr />
<p>显示喜欢的狗:</p>
<ul>
<li v-for="(item, index) in loveArr" :key="index">{{ item }}</li>
</ul>
</div>
</template>
<script>
import Dog from "./components/Dog4";
export default {
data() {
return {
// 1. 准备数据
arr: [
{
dogImgUrl:
"http://nwzimg.wezhan.cn/contents/sitefiles2029/10146688/images/21129958.jpg",
dogName: "博美",
},
{
dogImgUrl:
"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1224576619,1307855467&fm=26&gp=0.jpg",
dogName: "泰迪",
},
{
dogImgUrl:
"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2967740259,1518632757&fm=26&gp=0.jpg",
dogName: "金毛",
},
{
dogImgUrl:
"https://pic1.zhimg.com/80/v2-7ba4342e6fedb9c5f3726eb0888867da_1440w.jpg?source=1940ef5c",
dogName: "哈士奇",
},
{
dogImgUrl:
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1563813435580&di=946902d419c3643e33a0c9113fc8d780&imgtype=0&src=http%3A%2F%2Fvpic.video.qq.com%2F3388556%2Fd0522aynh3x_ori_3.jpg",
dogName: "阿拉斯加",
},
{
dogImgUrl:
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1563813454815&di=ecdd2ebf479568453d704dffacdfa12c&imgtype=0&src=http%3A%2F%2Fwww.officedoyen.com%2Fuploads%2Fallimg%2F150408%2F1-15040Q10J5B0.jpg",
dogName: "萨摩耶",
},
],
loveArr: [],
};
},
components: {
Dog,
},
methods: {
fn(dogName) {
this.loveArr.push(dogName);
},
},
};
</script>
<style >
</style>
./components/Dog4
<template>
<div class="my_dog">
<img :src="imgurl" alt="" />
<p :style="{ backgroundColor: colorStr }" @click="btn">{{ dogname }}</p>
</div>
</template>
<script>
export default {
props: ["imgurl", "dogname"],
data() {
return {
colorStr: "",
};
},
methods: {
btn() {
this.colorStr = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(
Math.random() * 256
)}, ${Math.floor(Math.random() * 256)})`;
// 补充: 触发父级事件
this.$emit("love", this.dogname);
},
},
};
</script>
<style scoped>
.my_dog {
width: 300px;
border: 1px solid black;
text-align: center;
float: left;
}
.my_dog img {
width: 100%;
height: 300px;
}
</style>
效果图
5.卖完了
App.vue
<template>
<div>
<table>
<!-- 2. 使用tr组件, 传入需要的数据 -->
<tr
is="myTr"
v-for="(item, index) in goodsArr"
:key="index"
:obj="item"
:index="index"
></tr>
</table>
<p>All Number:{{ sumNumber }}</p>
</div>
</template>
<script>
import MyTr from "./components/Dog5";
export default {
data() {
return {
goodsArr: [
{
count: 0,
goodsName: "Watermelon",
},
{
count: 0,
goodsName: "Banana",
},
{
count: 0,
goodsName: "Orange",
},
{
count: 0,
goodsName: "Pineapple",
},
{
count: 0,
goodsName: "Strawberry",
},
],
};
},
components: {
MyTr,
},
computed: {
sumNumber() {
return this.goodsArr.reduce((sum, obj) => (sum += obj.count * 1), 0);
},
},
};
</script>
<style>
</style>
./components/Dog5
<template>
<tr>
<td>
<input type="number" v-model.number="obj['count']"/>
</td>
<td>
<span>{{ obj["goodsName"] }}</span>
</td>
<td>
<span v-show="obj['count'] == 0">卖光了!!!</span>
</td>
</tr>
</template>
<script>
export default {
props: ["obj"]
};
</script>
<style>
</style>
效果图
6.买点好吃的
App.vue
<template>
<div>
<p>商品清单如下:</p>
<div v-for="(obj, index) in shopData" :key="index">
{{ obj.shopName }} -- {{ obj.price }}元/份
</div>
<p>请选择购买数量:</p>
<Food
v-for="(obj, index) in shopData"
:key="index + ' '"
:goodsname="obj.shopName"
:ind="index"
:count="obj.count"
@addE="addFn"
@secE="secFn"
>
</Food>
<p>总价为: {{ allPrice }}</p>
</div>
</template>
<script>
import Food from "./components/Dog6";
export default {
data() {
return {
// 商品数据
shopData: [
{
shopName: "可比克薯片",
price: 5.5,
count: 0,
},
{
shopName: "草莓酱",
price: 3.5,
count: 0,
},
{
shopName: "红烧肉",
price: 55,
count: 0,
},
{
shopName: "方便面",
price: 12,
count: 0,
},
],
};
},
components: {
Food,
},
methods: {
addFn(ind) {
this.shopData[ind].count++;
},
secFn(ind) {
this.shopData[ind].count > 0 && this.shopData[ind].count--;
},
},
computed: {
allPrice() {
return this.shopData.reduce(
(sum, obj) => (sum += obj.count * obj.price),
0
);
},
},
};
</script>
./components/Dog6
<template>
<div>
<span>{{ goodsname }}</span>
<button @click="add(ind)">+</button>
<span> {{ count }} </span>
<button @click="sec(ind)">-</button>
</div>
</template>
<script>
export default {
// 商品名,索引,数量
props: ["goodsname", "ind", "count"],
methods: {
add(ind) {
this.$emit("addF", ind);
},
sec(ind) {
this.$emit("secF", ind);
},
},
};
</script>
效果图
7.购物车
效果图
8.做数学题
App.vue
<template>
<div id="app">
<h2>测试题</h2>
<subject
v-for="(obj, index) in arr"
:key="index"
:one="obj.num1"
:two="obj.num2"
:index="index"
@celE="celFn"
></subject>
<div>
<flag
v-for="(obj, index) in arr"
:key="index"
:index="index"
:status="obj.isOk"
></flag>
</div>
</div>
</template>
<script>
// 组件-只负责数据展示, 逻辑全都回传给App.vue页面
// 需求: 完成做数学题
// 准备数据, 铺设页面
// Subject内, 获取结果, 点击提交
// 回传给App.vue事件方法, 计算结果, 影响isOk状态
// Flag内, 接收isOk状态的值和索引, 判断class, 判断文字
import Flag from "./components/Flag.vue";
import Subject from "./components/Subject.vue";
export default {
components: {
Flag,
Subject,
},
data() {
return {
arr: [
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
],
};
},
methods: {
celFn(index, result) {
let obj = this.arr[index]; // 题目对象
if (obj.num1 + obj.num2 === result) {
obj.isOk = "yes";
} else {
obj.isOk = "no"; // 题目回答错误
}
},
},
};
</script>
<style>
body {
background-color: #eee;
}
#app {
background-color: #fff;
width: 500px;
margin: 50px auto;
box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.5);
padding: 2em;
}
</style>
./components/Flag.vue
<template>
<span
:class="{
undo: status === 'unComplate',
right: status === 'yes',
error: status === 'no',
}"
>
{{ index + 1 }}:
{{
status === "unComplate" ? "未完成" : status === "yes" ? "正确" : "错误"
}}
</span>
</template>
<script>
export default {
// 'unComplate'
props: ["status", "index"],
};
</script>
<style scoped>
.right {
color: green;
}
.error {
color: red;
}
.undo {
color: #ccc;
}
</style>
./components/Subject.vue
<template>
<div class="subject">
<span>{{ one }}</span>
<span>+</span>
<span>{{ two }}</span>
<span>=</span>
<input type="number" v-model.number="result" :disabled="isCheck" />
<button @click="sendFn" :disabled="isCheck">提交</button>
</div>
</template>
<script>
export default {
props: ["one", "two", "index"],
data() {
return {
result: "",
isCheck: false, // 是否关闭按钮和输入框
};
},
methods: {
sendFn() {
this.$emit("celE", this.index, this.result);
// 关闭输入框和按钮
this.isCheck = true;
},
},
};
</script>
<style scoped>
.subject {
margin: 5px;
padding: 5px;
font-size: 20px;
}
.subject span {
display: inline-block;
text-align: center;
width: 20px;
}
.subject input {
width: 50px;
height: 20px;
}
</style>
7.购物车
<template>
<div>
<table border="1" width="700" style="border-collapse: collapse">
<caption>
购物车
</caption>
<thead>
<tr>
<th><input type="checkbox" v-model="isAll"/> <span>全选</span></th>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>总价</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(obj, index) in goodList" :key="index">
<th><input type="checkbox" v-model="obj.checked"/> <span></span></th>
<th>{{ obj.name }}</th>
<th>{{ obj.price }}</th>
<th>
<button @click="add(index)">+</button>
<span>{{ obj.num }}</span>
<button @click="sec(index)">-</button>
</th>
<th>{{ obj.price * obj.num }}</th>
<th><button @click="out(index)">删除</button></th>
</tr>
</tbody>
<tfoot>
<tr>
<td>合计:{{ allPrice }}</td>
<td colspan="5"></td>
</tr>
</tfoot>
</table>
</div>
</template>
<script>
export default {
data() {
return {
goodList: [
{
name: "诸葛亮",
price: 1000,
num: 1,
checked: false,
},
{
name: "蔡文姬",
price: 1500,
num: 1,
checked: false,
},
{
name: "妲己",
price: 2000,
num: 1,
checked: false,
},
{
name: "鲁班",
price: 2200,
num: 1,
checked: false,
},
],
};
},
methods: {
add(index) {
this.goodList[index].num++;
},
sec(index) {
if (this.goodList[index].num !== 0) {
this.goodList[index].num--;
}
},
out(index) {
this.goodList.splice(index, 1);
},
},
computed: {
allPrice() {
return this.goodList.reduce((sum, obj) => {
return (sum += obj.price * obj.num);
}, 0);
},
isAll:{
set(val){
// console.log(val);
return this.goodList.forEach(obj=>obj.checked = val)
},
get() {
return this.goodList.every(obj=>obj.checked === true)
}
}
},
};
</script>
<style>
</style>
8.做数学题
App.vue
<template>
<div id="app">
<h2>测试题</h2>
<subject
v-for="(obj, index) in arr"
:key="index"
:one="obj.num1"
:two="obj.num2"
:index="index"
@celE="celFn"
></subject>
<div>
<flag
v-for="(obj, index) in arr"
:key="index"
:index="index"
:status="obj.isOk"
></flag>
</div>
</div>
</template>
<script>
// 组件-只负责数据展示, 逻辑全都回传给App.vue页面
// 需求: 完成做数学题
// 准备数据, 铺设页面
// Subject内, 获取结果, 点击提交
// 回传给App.vue事件方法, 计算结果, 影响isOk状态
// Flag内, 接收isOk状态的值和索引, 判断class, 判断文字
import Flag from "./components/Flag.vue";
import Subject from "./components/Subject.vue";
export default {
components: {
Flag,
Subject,
},
data() {
return {
arr: [
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
{
num1: Math.floor(Math.random() * 10),
num2: Math.floor(Math.random() * 10),
isOk: "unComplate", // 未完成
},
],
};
},
methods: {
celFn(index, result) {
let obj = this.arr[index]; // 题目对象
if (obj.num1 + obj.num2 === result) {
obj.isOk = "yes";
} else {
obj.isOk = "no"; // 题目回答错误
}
},
},
};
</script>
<style>
body {
background-color: #eee;
}
#app {
background-color: #fff;
width: 500px;
margin: 50px auto;
box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.5);
padding: 2em;
}
</style>
./components/Flag.vue
<template>
<span
:class="{
undo: status === 'unComplate',
right: status === 'yes',
error: status === 'no',
}"
>
{{ index + 1 }}:
{{
status === "unComplate" ? "未完成" : status === "yes" ? "正确" : "错误"
}}
</span>
</template>
<script>
export default {
// 'unComplate'
props: ["status", "index"],
};
</script>
<style scoped>
.right {
color: green;
}
.error {
color: red;
}
.undo {
color: #ccc;
}
</style>
./components/Subject.vue
<template>
<div class="subject">
<span>{{ one }}</span>
<span>+</span>
<span>{{ two }}</span>
<span>=</span>
<input type="number" v-model.number="result" :disabled="isCheck" />
<button @click="sendFn" :disabled="isCheck">提交</button>
</div>
</template>
<script>
export default {
props: ["one", "two", "index"],
data() {
return {
result: "",
isCheck: false, // 是否关闭按钮和输入框
};
},
methods: {
sendFn() {
this.$emit("celE", this.index, this.result);
// 关闭输入框和按钮
this.isCheck = true;
},
},
};
</script>
<style scoped>
.subject {
margin: 5px;
padding: 5px;
font-size: 20px;
}
.subject span {
display: inline-block;
text-align: center;
width: 20px;
}
.subject input {
width: 50px;
height: 20px;
}
</style>