zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Vue3中多个v-model绑定

Vue3 多个 绑定 model
2023-06-13 09:13:42 时间

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

<!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的绑定

其中最核心的代码:

@input="$emit('update:firstName', $event.target.value)">