Vue3中props和emits的使用介绍
1,看代码
1.1,App.vue
<script setup>
import { ref,reactive } from 'vue'
import TodoItem from './TodoItem.vue'
const todos = ref([
{
id: 1,
title: 'Do the dishes'
},
{
id: 2,
title: 'Take out the trash'
},
{
id: 3,
title: 'Mow the lawn'
}
])
const item = reactive({
id: 100,
title: '你删不掉的,哈哈哈'
})
</script>
<template>
<ul>
<todo-item
v-for="(todo, index) in todos"
:key="todo.id"
:title="todo.title"
@remove="todos.splice(index, 0,item)"
></todo-item>
</ul>
</template>
1.2,TodoItem.vue
<script setup>
// 父传子用Props
defineProps(['title'])
// 子调父定义的操作用Emits
defineEmits(['remove'])
</script>
<template>
<li>
{{ title }}
<button @click="$emit('remove')">Remove</button>
</li>
</template>
2,总结
2.1 props
在Vue3中,使用defineProps
函数接受父组件传过来的props对象,
2.2 emits
在Vue3中,通过defineEmits
函数使用父组件对当前行为的定义操作,可以使得具体实现不用在子组件中具体定义,完全交由父组件去定义即可,以此达到组件化开发解耦的目的