🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## TodoLIst [小程序-TodoList](https://www.kancloud.cn/book/henputongderen/xiaochengxu/edit) [React](https://www.kancloud.cn/book/henputongderen/react/edit) ## 功能介绍 > 将input输入框里的内容打印到页面上,可以输入多条,并可以点击删除 > 知识点组件传值 ![](https://box.kancloud.cn/b23d789c5d7f08540b4caea66e792280_506x418.gif) ## 知识细分 ### 1.使用组件 ``` 1.定义组件 name: "ListItem", 2.引入组件 import ListItem from "../components/ListItem"; 3.注册组件 components: { ListItem }, 4.使用组件 <list-item v-for="(item, index) of list" :key="index" :content="item" :index="index" @delete="handleDelete" ></list-item> ``` ### 2.组件传值 #### 父向子传 ``` 1.传值 <list-item v-for="(item, index) of list" :key="index" :content="item" :index="index" @delete="handleDelete" ></list-item> ``` ``` 2.接值 props: { index:Number, content:String }, ``` #### 子向父 ``` 1.传值 绑定事件: @click="handleClick" methods: { handleClick(){ this.$emit('delete',this.index) } }, ``` ``` 2.接值 绑定事件:@delete="handleDelete" handleDelete(index) { this.list.splice(index, 1); } ``` ## 完整代码 ### Home.vue ``` <template> <div class="home"> <input type="text" v-model="value"> <button @click="handleClick">确定</button> <ul> <list-item v-for="(item, index) of list" :key="index" :content="item" :index="index" @delete="handleDelete" ></list-item> </ul> </div> </template> <script> import ListItem from "../components/ListItem"; export default { name: "home", components: { ListItem }, data() { return { value: "hello", list: [] }; }, methods: { handleClick() { if (!this.list.includes(this.value)) { this.list.unshift(this.value); } }, handleDelete(index) { this.list.splice(index, 1); } } }; </script> ``` ### ListItem.vue ``` <template> <li @click="handleClick">{{content}}</li> </template> <script> export default{ name: "ListItem", props: { index:Number, content:String }, methods: { handleClick(){ this.$emit('delete',this.index) } }, } </script> ```