Vue之父子组件传值

xiaoxiao2021-02-28  42

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputValue"> <button @click="handleBtnClick">提交</button> <ul> <todo-item v-bind:content="item" :index="index" v-for="(item,index) in list" //父级组件方法☆ @delete="handleDeleteMove" >{{ item }}</todo-item> </ul> </div> <script> <!----> let TodoItem = { //子组件必须接受值★ props: ['content','index'], //每一行内容点击 template: '<li @click="handleItemClick">{{ content }}</li>', methods:{ handleItemClick:function () { //使用索引时this.index this.$emit('delete',this.index) }, } }; let app = new Vue({ el: '#app', components: { TodoItem: TodoItem }, data: { list: [], inputValue: '' }, methods: { handleBtnClick() { this.list.push(this.inputValue); this.inputValue = '' }, handleDeleteMove:function (index) { this.list.splice(index,1) } } }) </script> </body> </html>

父组件给子组件传值,子组件需要用v-bind定义,然后在子组件的props中接收:

<todo-item v-bind:content="item" :index="index" v-for="(item,index) in list" //父级组件方法☆ @delete="handleDeleteMove" >{{ item }}</todo-item> let TodoItem = { //子组件必须接受值★ props: ['content','index'],

子组件给父组件传值,子组件需要用this.$emit,触发父组件的方法:

this.$emit('delete',this.index) @delete="handleDeleteMove" handleDeleteMove:function (index) { this.list.splice(index,1) }
转载请注明原文地址: https://www.6miu.com/read-2614762.html

最新回复(0)