#咕咕咕咕咕咕咕咕#
本文章仅用作于个人学习笔记(蓝后我就可以乱写啦)复制代码
接上一文章 利用Vue-CLi实现一个简单的TodoList工具
一、组件化的优点
当TodoList的todo item越来越多的时候,我们应该把它拆分成一个组件进行开发,维护。组件的出现,就是为了拆分Vue实例的代码量,让我们以不同的组件,来划分成不同功能模块,然后拼接成一个完整的页面。将来需要怎样的功能,就去调对应的组件就好了。
目前我能理解的组件化开发的优点如下:
1) 提高开发效率。
2) 方便重复使用。
3) 提升可维护性。复制代码
插一张官方文档的图:
二、注册组件
在脚手架中我们选中使用 .vue单文件来开发。一个.vue文件中具有完整的 template(html)、script、style标签。
.vue的单文件可以获得:
1) 完整语法高亮
2) CommonJS 模块
3) 组件作用域的 CSS ( <style scoped></style> ) 复制代码
1.先创建一个TodoList.vue文件到components文件夹下,创建完后,我们需要在根组件App.vue中引入TodoList.vue并注册组件。
//导入的组件需要放入components中复制代码
查看是否引入成功:
2.接下来我们把之前的li标签的内容移植到TodoList.vue中。父子组件之间的通行我们使用props和$emit。
- 子组件使用 props 来接收 父组件传来的值
- 子组件使用 $emit 将事件和数据 发射出去。需要子组件数据的父组件添加一个自定义事件用来监听子组件
1)在父组件(App.vue)的todo-item中把数据“绑定到”自定义属性 :content(item的文字) , :time(item的创建时间), :index(数组的下标),并添加事件@delect监听子组件的事件
<todo-item
v-for="(item,index) in list"
:key="index"
:content="item.text"
:time="item.time"
:index="index"
@delect="handleDelect"
></todo-item>
复制代码
2)子组件(TodoList.vue)通过props来接收父组件传来的数据渲染页面。创建点击事件调用方法handleDelect方法,方法中使用 $emit 将下标index发射出去(父组件接收用来删除对应的item)
<template>
<li>
<div>{{content}}</div>
<small>
<span>创建于:{{time}}</span>
</small>
<button @click="handleDelect">删除</button>
</li>
</template>
<script>
export default {
props: ["content", "time", "index"],
methods: {
handleDelect() {
this.$emit("delect", this.index);
}
}
};
</script>
复制代码
完整代码:
App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<div>
<div>
<input type="text" placeholder="添加便签" v-model.trim="inputValue">
<button @click="handleSubmit">添加</button>
</div>
<ul>
<!-- 把这个组件作为自定义元素来使用 -->
<todo-item
v-for="(item,index) in list"
:key="index"
:content="item.text"
:time="item.time"
:index="index"
@delect="handleDelect"
></todo-item>
</ul>
</div>
</div>
</template>
<script>
// import (引入文件的文件命名) from ("文件的路径")
import todolist from "./components/TodoList.vue";
export default {
name: "app",
// ("组件名"() : (引入文件的文件命名)
components: {
"todo-item": todolist
},
data() {
return {
inputValue: "",
list: []
};
},
methods: {
handleSubmit() {
if (this.inputValue != "") {
this.list.push({
text: this.inputValue,
time: new Date().toLocaleString()
});
this.inputValue = "";
}
},
handleDelect(index) {
this.list.splice(index, 1);
}
}
};
</script>复制代码
TodoList.vue
<template>
<li>
<div>{{content}}</div>
<small>
<span>创建于:{{time}}</span>
</small>
<button @click="handleDelect">删除</button>
</li>
</template>
<script>
export default {
props: ["content", "time", "index"],
methods: {
handleDelect() {
this.$emit("delect", this.index);
}
}
};
</script>
<style scoped>
</style>复制代码
错误可能很多,但我现在还没看出来hhhhh