vue3进阶-自定义组件双向绑定(modelValue)
vue3 自定义组件双向绑定 modelValue的使用
·
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
// 双向绑定一
const HelloWorld = {
props: ['modelValue'], // modelValue为约定俗成字段,就是父组件传来的v-model绑定的值
template: `<div>
{{modelValue}}
<button @click="handleClick">计算</button>
</div>`,
methods: {
handleClick() { // update:modelValue也是固定的
this.$emit('update:modelValue', this.modelValue + 5)
}
},
}
const app = Vue.createApp({
components: { HelloWorld },
template: `<div>
<hello-world v-model="count"/>
</div>`,
data(){
return {
count: 0,
}
}
})
app.mount('#root')
</script>
<div id="root1"></div>
<script>
// 双向绑定2: // 这样可以同时绑定多个v-model
const test = {
props: ['num', 'n'], // 如果要自定义字段,那么父组件中v-model后需要绑定这个字段
template: `<div>
{{num}} - {{n}}
<button @click="handleClick2">计算</button>
</div>`,
methods: {
handleClick2() {
this.$emit('update:num', this.num + 5)
this.$emit('update:n', this.n + 2)
}
},
}
const App = Vue.createApp({
components: { test },
template: `<div>
<test v-model:num="count" v-model:n="n"/>
</div>`,
data(){
return {
count: 0,
n: 0
}
}
})
App.mount('#root1')
</script>
</body>
</html>
更多推荐
所有评论(0)