HMVue2.3.4【(4)双向绑定指令】

 1 双向数据绑定指令

 

<!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>
</head>
<body>

    <div id="app">
        <p>用户名:{{username}}</p>
        <input type="text" v-model="username">  <!-- v-model双向绑定,数据源和页面双向 -->
        <hr>
        <input type="text" value="abc">
        <input type="text" :value="username">  <!-- v-bind单向绑定,仅数据源到页面 -->
        <hr>
        <!-- v-model在表单元素中使用才有意义,在div等这种中使用无意义 -->
        <select v-model="city">
            <option value="">---请选择---</option>
            <option value="1">北京</option>
            <option value="2">上海</option>
            <option value="3">广州</option>
            <option value="4">深圳</option>
        </select>
    </div>

    <script src="./lib/vue-2.6.12.js"></script>
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                username: 'zhangsan',
                city: '2', //默认值设为2
            }
        })
    </script>

</body>
</html>

 

 

 

 2 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>
</head>
<body>

    <div id="app">
        <input type="text" v-model="n1"> 
        + <input type="text" v-model="n2"> 
        = <span>{{ n1 + n2 }}</span>
        <hr>
        <input type="text" v-model.number="n3"> 
        + <input type="text" v-model.number="n4"> 
        = <span>{{ n3 + n4 }}</span>
        <hr>
        <input type="text" v-model="username">
        <button @click="showName1">获取用户名</button>
        <hr>
        <input type="text" v-model.trim="username2">
        <button @click="showName2">获取用户名</button>
        <hr>
        <input type="text" v-model="username">
        <input type="text" v-model.lazy="username">
    </div>

    <script src="./lib/vue-2.6.12.js"></script>
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                username: 'zhangsan',
                n1: 1,
                n2: 2,
                n3: 1,
                n4: 2,
                username2: 'lisi',
            },
            methods: {
                showName1(){
                    console.log(`用户名是:"${this.username}"`)
                },
                showName2(){
                    console.log(`用户名是:"${this.username2}"`)
                },
            },  
        })
    </script>

</body>
</html>

 

 

 

 

 

 

 

 

 

posted @ 2021-11-17 18:36  yub4by  阅读(44)  评论(0)    收藏  举报