Vue2到Vue3的一个很大的变动就是父子组件之间的通信,在Vue2时我们是这样的:在父组件中定义一个变量,子组件通过props
获取到这个变量的值,通常情况下我们是想要修改这个值的,但是子组件是没有权限修改父组件变量的值,这就产生了emit
和$event
,emit
用在子组件中,常用的有两个参数,第一个参数是事件名,第二个参数是事件参数,当然事件名是可以自己随便定义的,在父组件中使用$event
取到修改后的内容,然后将这个值修改
代码实例:
父组件:
<template>
<Switch :value="y" @update:value="y = $event" />
</template>
<script lang="ts">
import Switch from '../lib/Switch.vue'
import {ref} from "vue";
export default {
components:{Switch},
setup(){
const y = ref(true)
return {y}
}
}
</script>
子组件(Switch.vue):
<template>
<button :class="{checked:value}" @click="toggle">
</template>
<script lang="ts">
export default {
props: {
value: Boolean
},
setup(props,context){ //用来做初始化
const toggle = () => {
//emit的第一个参数是事件名,第二个参数是事件参数,Vue3中事件名必须是update:value
context.emit('update:value',!props.value) //将value的值取反,通过input事件将它发送到外面
}
return {toggle}
}
};
</script>
在Vue3中,提供了v-model,为我们简化了代码,实例如下:
父组件:
<template>
<Switch v-model:value="y" />
</template>
<script lang="ts">
import Switch from '../lib/Switch.vue'
import {ref} from "vue";
export default {
components:{Switch},
setup(){
const y = ref(true)
return {y}
}
}
</script>
子组件(Switch.vue):
<template>
<button :class="{checked:value}" @click="toggle">
</template>
<script lang="ts">
export default {
props: {
value: Boolean
},
setup(props,context){ //用来做初始化
const toggle = () => {
//emit的第一个参数是事件名,第二个参数是事件参数,Vue3中事件名必须是update:value,如果这个变量叫x,就要写成update:x
context.emit('update:value',!props.value) //将value的值取反,通过input事件将它发送到外面
}
return {toggle}
}
};
</script>