v-model 和 v-model:[update:xxxxx]相关用法

168 阅读1分钟
1. v-model 绑定响应式数据 同vue2
let textVal = ref(1)
template
<input v-model="textVal" type="text"/>
2. <子组件 v-model:xxx = data> </子组件>,自组件触发改变data时的用法:
// Parent.vue
let textVal = ref(1)
// 计时器
setInterval(() => {
  textVal.value += 1
}, 1000)
//自定义绑定 和  默认绑定
<Child v-model:parentModel=textVal v-model = textVal></Child>
// Child.vue
// 接收父组件 props 属性
const props = defineProps({
  modelValue: {
    default: 0,
    require: true
  },
  parentModel: {
    default: 0,
    require: true
  }
})
// 声明一下
const emit = defineEmits(['update:modelValue', 'update:parentModel'])
const clickBtn = () => { // 默认触发 update:modelValue
  emit('update:modelValue', 0) // 点击重置为 0 计时
}
const clickBtn1 = () => { // 自定义触发: update:xxx (自定义名称)
  emit('update:parentModel', 100)// 点击重置为从 100 计时
}

// template
 Child组件:
    <button @click="clickBtn">Child按钮: 归零 {{ modelValue }}</button>
    <button @click="clickBtn1">Child按钮: 从100开始: {{ parentModel }}</button>