Search code examples
htmlvue.jsantd

How to get the correct data while using Ant Desgin + Vue in HTML


I'm working on Ant Design Vue in HTML pages When I did use antd but Vue only, everything worked fine. But when I introduced antd in, I just couldn't get the data of inputbox correctly. Here's the code:

<head>
    <?php $this->head() ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ant-design-vue@3/dist/antd.min.css">
</head>
<body>
<?php $this->beginBody() ?>

<div id="app">
    <div class="login-container">
        <a-form @submit.prevent="handleSubmit">
            <a-form-item>
                <a-input v-model="username"></a-input>
            </a-form-item>
            <a-form-item>
                <a-input type="password" v-model="password"></a-input>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" htmlType="submit" @click="handleSubmit" block>Login</a-button>
            </a-form-item>
        </a-form>
    </div>
</div>

//bunches of scripts included...
<script src="https://cdn.jsdelivr.net/npm/ant-design-vue@3/dist/antd.min.js"></script>

<script>
    const app = Vue.createApp({
        data() {
            return {
                username: '',
                password: ''
            };
        },
        methods: {
            handleSubmit() {
                axios.post('http://api.yanglao.local/auth/login', {
                    username: this.username,
                    password: this.password
                }).then(response => {
                    if (response.data.success) {
                        alert('SUCCESS');
                    } else {
                        alert('FAIL: ' + response.data.message);
                    }
                }).catch(error => {
                    console.error('FAIL IN REQUEST: ', error);
                });
            }
        }
    });
    Object.values(antd).forEach(o => {
        if (typeof o == "object" && o.name) {
            app.component(o.name, o);
        }
    });
    app.mount("#app");
</script>

<?php $this->endBody() ?>
</body>
</html>

I can invoke the handleSubmit() correctly but this.username and this.password was always empty. Any guy has any clue about this?


Solution

  • Two-way binding with a-input is accomplished using v-model:value

    <a-form-item>
        <a-input v-model:value="username"></a-input>
    </a-form-item>
    <a-form-item>
        <a-input type="password" v-model:value="password"></a-input>
    </a-form-item>
    

    Documentation