vue父子元件之間通訊例項
阿新 • • 發佈:2018-11-07
一、父元件向子元件傳遞資料
①獲取資料並在父元件上繫結資料
②在子元件使用props接收父元件傳遞過來資料
③將接收的資料繫結到子元件模板
二、子元件向父元件傳遞資料
①在子元件上定義一個事件 如 @click='handleItemClick'
②在這個方法裡面使用this.$emit方法提交一個自定義事件,如 this.$emit("delete",this.index);
③在父元件監聽這個自定義事件 如: @delete="handleItemDelete"
④在這個事件的方法裡面操作父元件的資料 :如
handleItemDelete: function() {
this.list.splice(index,1)
}
<body> <div id="app"> <input type="text" v-model="inputValue" /> <button v-on:click="handleBtnClick">提交</button> <ul> <todo-item :content="item" :index="index" v-for="(item, index) in list" @delete="handleItemDelete"> </todo-item> </ul> </div> <script> var TodoItem = { props: ['content', 'index'], template: "<li @click='handleItemClick'>{{content}}</li>", methods: { handleItemClick: function() { this.$emit("delete",this.index); } } } var app = new Vue({ el: '#app', components: { TodoItem: TodoItem }, data: { list: [], inputValue: '' } }) methods: { handleBtnClick: function() { this.list.push(this.inputValue) this.inputValue = '' }, handleItemDelete: function() { this.list.splice(index,1) } } </script> <body>