vue3 父子组件双向绑定
之前是用emit=['update:xxx']这种方式实现的,今天忘记细节了无意中发现v-model竟然有用,具体为什么我还不太清楚。这样就可以实现双向传值了。
·
父组件
<template>
<button @click="changeVisible">按钮<button>
<Inner v-model="visible"/>
</template>
<script setup>
import Inner from './inner'
import { ref } from 'vue'
const visible = ref(false)
const changeVisible = () => {
visible.value = true
}
</script>
子组件
<template>
<div v-show="visible">
<button @click="visible = false">关闭</button>
</div>
</template>
<script setup>
</script>
这样就可以实现双向传值了
之前是用emit=['update:xxx']这种方式实现的,今天忘记细节了无意中发现v-model竟然有用,具体为什么我还不太清楚
补充: v-model:属性=“父组件的值” 并使用update可实现双向绑定,话不多说直接上代码
父组件
<template>
<son v-model:heritage="list" />
{{ list }}
</template>
<script setup>
import son from './son.vue'
import { ref } from 'vue'
const list = ref(1)
</script>
子组件
<template>
<button @click="add">{{ heritage }}</button>
</template>
<script setup>
import { defineProps, defineEmits, computed } from 'vue'
const props = defineProps({
heritage: {
type: Number,
default: 1 // 还有其他选项像是必填之类的,还有如果是引用数据类型要default一个函数,这里不
// 赘述了
}
})
const emits = defineEmits(['heritage'])
const heritage = computed({
get () {
return props.heritage
},
set (heritage) {
emits('update:heritage', heritage)
}
})
const add = () => {
heritage += 1
emits('update:heritage', heritage) // 可写可不写,防止失效保底作用
}
</script>
这样就实现了数据双向绑定,一开始说那种虽然简单,但是只能绑定一个属性,这种方法可以绑定多个
更多推荐
已为社区贡献6条内容
所有评论(0)