vue3.0 カスタム v モデル
親コンポーネント
// 父组件
<template>
<div class="box">
<ul>
<li>子父组件双向绑定的值{
{
testData}}</li>
</ul>
<!-- 自定义的v-model后面一定要跟:xxx xxx是你子组件接受的props值 -->
<Child v-model:modelValue="testData" data="12312412"></Child>
</div>
</template>
<script lang="ts">
import {
defineComponent, ref } from 'vue'
import Child from './child.vue'
export default defineComponent({
components:{
Child
},
setup() {
const testData = ref('1234')
return {
testData
}
}
})
</script>
サブアセンブリ
<template>
<div class="box">
<div class="box">子组件</div>
<button @click="handelChange">点我改父组件值</button>
</div>
</template>
<script>
import {
defineComponent, reactive, toRefs } from 'vue'
export default defineComponent({
props:{
test:{
type: Object,
default: () => {
return {
} }
},
modelValue: {
type: [String,Number],
default: ''
}
},
setup(props, {
emit }) {
const {
modelValue } = toRefs(props) // 必须保持ref属性,不然父组件的更新子组件监听不到 `
const handelChange = () => {
const val = '666' // 要改的值
emit('update:modelValue', val)
}
return {
handelChange
}
}
})
</script>
コードをコピーしてみてください