Vue——TodoList父子组件通信
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>TodoList</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="root"> <div> <input type="text" v-model="inputValue" /> <button @click="subValue">提交</button> </div> <ul> <todo-item v-for="(item, index) of list" :ket="index" :content="item" :index="index" @delete="handleDelete"></todo-item> </ul> </div> <script type="text/javascript"> // 全局组件 Vue.component('todo-item', { props: ['content', 'index'], template: '<li @click="todoClick">{{content}} {{index}}</li>', methods: { todoClick: function() { alert("clicked") this.$emit("delete", this.index) //子父组件通信 } } }) // 局部组件 // var TodoItem = { // template: '<li>item</li>' // } new Vue({ el: '#root', //局部组件 // components: { // TodoItem, // }, data: { inputValue: "", list: [], }, methods: { subValue: function() { this.list.push(this.inputValue) this.inputValue = "" }, handleDelete:function(index){ alert(index) this.list.splice(index,1) } } }) </script> </body> </html>
___________________________________cli______________________________________
TodoList.vue
<template> <div> <input type="text" v-model="inputValue" /> <button @click="subBtn">提交</button> <ul> <todo-item v-for="(item, index) of list" :key="index" :content="item" :index="index" @delete="deleteItem" ></todo-item> </ul> </div> </template> <script> import TodoItem from "./components/TodoItem"; export default { components: { TodoItem }, data() { return { inputValue: "", list: [] }; }, methods: { subBtn() { this.list.push(this.inputValue); this.inputValue = ""; }, deleteItem(index) { this.list.splice(index, 1); } } }; </script>
TodoItem.vue
<template> <li @click="deleteClick">{{content}} {{index}}</li> </template> <script> export default { name: "TodoItem", props: ["content", "index"], methods: { deleteClick() { this.$emit("delete", this.index); } } }; </script>
略懂,略懂....