完整例子: https://www.cnblogs.com/landv/p/11110822.html
https://cn.vuejs.org/v2/api/#vm-emit
vm.$emit( eventName, […args] )
触发当前实例上的事件。附加参数都会传给监听器回调。
v-on(绑定监听事件)
app.vue(这里)
<template>
<div id="app">
<AddTodo v-on:handleAddEmit="handleAdd"/>
<Todos :todos="todos" @handleDelete="handleDelete"/>
</div>
</template>
<script>
import Todos from "./components/Todos";
import AddTodo from "./components/AddTodo";
export default {
name:"app",
data(){
return{
todos:[
{
id:1
},
{
id:2
},
{
id:3
},
]
}
},
components:{
Todos,
AddTodo,
},
methods:{
handleDelete(id){
// console.log(id);
this.todos=this.todos.filter(todo =>todo.id !==id)
},
handleAdd(newTodo){
// this.todos.unshift(newTodo);
this.todos=[...this.todos,newTodo]
}
}
}
</script>
<style>
*{
box-sizing:border-box;
margin: 0;
padding: 0;
}
body{
font-family: Arial, Helvetica, sans-serif;
line-height: 1.4;
}
</style>
AddTodo.vue
<template>
<div>
<form @submit="addTodo">
<input type="submit" value="添加uuid" class="btn">
</form>
</div>
</template>
<script>
import uuid from "uuid";
export default {
name:"AddTodo",
data(){
return{}
},
methods:{
addTodo(e){
e.preventDefault();
// console.log('title:', this.title)
const newTodo={
id:uuid.v4(),
};
console.log('tag',newTodo )
//注册事件
this.$emit("handleAddEmit",newTodo)
}
}
}
</script>
<style scoped>
form{
display:flex;
}
input[type="text"]{
flex:10;
padding: 5px;
}
input[type="submint"]{
flex: 2;
}
.btn{
display: inline-block;
border: none;
background: #555;
color:#fff;
padding:7px 20px;
cursor: pointer;
}
.btn:hover{
background: #666;
}
</style>
Todos.vue
<template>
<div>
<div :key="todo.index" v-for="(todo) in todos">
<!-- <Todoitem :todo="todo" @deleteItem="deleteItem"/> -->
<Todoitem :todo="todo" @deleteItem="$emit('handleDelete',todo.id)"/>
</div>
</div>
</template>
<script>
import Todoitem from './Todoitem';
export default {
name:"Todos",
props:{
todos:{
type:Array
}
},
components:{
Todoitem
},
methods:{
// deleteItem(id){
// console.log(id);
// }
}
};
</script>
<style scoped>
</style>
Todoitem.vue
<template>
<div class="todo-item" :class="{'is-complete':todo.completed}">
<p>
<input type="checkbox" @change="markComplete">
{{todo.id}}
<button class="del" @click="$emit('deleteItem',todo.id)">x</button>
</p>
</div>
</template>
<script>
export default {
name:"Todos",
props:["todo"],
methods:{
markComplete(){
// console.log(this.todo);
this.todo.completed = !this.todo.completed;
}
}
}
</script>
<style scoped>
.todo-item{
background: #f4f4f4;
padding: 10px;
border-bottom: 1px #ccc dotted;
}
.is-complete{
text-decoration: line-through;
}
.del{
background: #ff0000;
color: #fff;
border: none;
padding: 5px 9px;
border-radius: 50%;
cursor: pointer;
float: right;
}
</style>