Vue3中多个v-model绑定

2022-10-04 12:02:09 浏览数 (1)

Vue3中多个v-model如何绑定,直接上代码,比较符合码农干脆利落的办事风格:

代码语言:javascript复制
<!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@3/dist/vue.global.js"></script>
</head>

<body>

    <div id="app" class="demo">
        <p>First name: {{ firstName }}</p>
        <p>Last name: {{ lastName }}</p>
        <user-name v-model:first-name="firstName" v-model:last-name="lastName"></user-name> <!--多个v-model绑定-->
    </div>
    <script src="https://unpkg.com/vue@next"></script>
    <script>
        const app = Vue.createApp({});
        const UserName = {
            props: {
                firstName: String,
                lastName: String
            },
            /* emits: ['update:firstName', 'update:lastName'],*/
            template: `
    <input 
      type="text"
      :value="firstName"
      @input="$emit('update:firstName', $event.target.value)">

    <input
      type="text"
      :value="lastName"
      @input="$emit('update:lastName', $event.target.value)">
  `
        };
        const HelloVueApp = {
            components: {
                UserName,
            },
            data() {
                return {
                    firstName: 'John',
                    lastName: 'Doe',
                };
            },
        };
        Vue.createApp(HelloVueApp).mount('#app')
    </script>




</body>

</html>

运行效果如下:

多个v-model的绑定多个v-model的绑定

其中最核心的代码:

代码语言:javascript复制
@input="$emit('update:firstName', $event.target.value)">

0 人点赞