本文章仅用作于个人学习笔记(蓝后我就可以乱写啦)复制代码
目前我能理解的组件化开发的优点如下:
1) 提高开发效率。2) 方便重复使用。3) 提升可维护性。复制代码插一张官方文档的图:
二、注册组件在脚手架中我们选中使用 .vue单文件来开发。一个.vue文件中具有完整的 template(html)、script、style标签。
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>
<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"> <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