父子组件传递数据

xiaoxiao2025-07-31  9

效果(输入数据,点击按钮提交。点击数据可删除) 父-子:父组件通过v-band绑定数据,子组件props接收数据子-父:子组件通过$emit触发父组件的自定义事件并且传递数据,父组件通过监听事件接收。代码 (本地引用了vue.js) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>父子组件之间传值</title> <script src="vue.js"></script> <style> li{cursor:pointer;} </style> </head> <body> <div id="app"> <input type="text" v-model="inputValue"> <button @click="handleBtnClick">按钮</button> <ul> <todo-item :content="item" :index="index" v-for="(item, index) of list" :key="index" @delete = 'handleItemDelete'> <!--监听delete事件--> </todo-item> </ul> </div> <script> var TodoItem = { //子组件接收父组件传递来的数据 props: ['content','index'], template: '<li @click="handleItemClick">{{content}}</li>', methods: { handleItemClick: function () { //$emit子组件触发父组件的自定义事件(delete),并且传递数据(index) this.$emit('delete',this.index) } } } var app = new Vue({ el: '#app', components:{ TodoItem }, data: { list: [], inputValue: '' }, methods: { handleBtnClick: function () { this.list.push(this.inputValue) this.inputValue = '' }, handleItemDelete: function (index) { this.list.splice(index,1) } } }) </script> </body> </html> 上一篇博客 简单的vue编写TodoList(未使用组件)

如有错误,望各位大佬指正。

转载请注明原文地址: https://www.6miu.com/read-5034063.html

最新回复(0)