文本

v-model会根据控件类型自动选择正确的方法来更新元素

var test1=new Vue({
    el:'#test1',
    data:{
        name:'legroft',
        describe:'22岁\r\n是学生'
    }
});
<div id="test1">
    <input v-model="name" placeholder="输入name">
    <p>name: {{name}}</p>
    <textarea v-model="describe" placeholder="输入简介"></textarea>
    <p>简介:</p>
    <p style="white-space: pre">{{describe}}</p>
</div>

结果:

复选框与单选按钮

多个复选框可以绑定到一个数组

var test2=new Vue({
    el:'#test2',
    data: {
        checkedNames:[]
    }
});
<div id="test2">
    <input type="checkbox" id="alice" value="Alice" v-model="checkedNames">
    <label for="alice">Alice</label>
    <input type="checkbox" id="bob" value="Bob" v-model="checkedNames">
    <label for="bob">Bob</label>
    <input type="checkbox" id="cap" value="Cap" v-model="checkedNames">
    <label for="cap">Cap</label>
    <br>
    <span>选中的名字:{{checkedNames}}</span>
</div>

结果:

单选按钮

var test3=new Vue({
    el:'#test3',
    data:{
        picked:'Chrome'
    }
});
<div id="test3">
    <input type="radio" id="chrome" value="Chrome" v-model="picked">
    <label for="chrome">Chrome</label>
    <input type="radio" id="firefox" value="FireFox" v-model="picked">
    <label for="firefox">FireFox</label>
    <br>
    <span>选中的浏览器:{{picked}}</span>
</div>

结果:

选择框

单选选择框

var test4=new Vue({
    el:'#test4',
    data:{
        selected:''
    }
});
<div id="test4">
    <select v-model="selected">
        <option disabled value="">请选择选项</option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>
    <span>选择了:{{selected}}</span>
</div>

结果:

多选选择框

var test5=new Vue({
    el:'#test5',
    data:{
        selected:[]
    }
});
<div id="test5">
    <select v-model="selected" multiple>
        <option disabled value="">请选择选项</option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>
    <span>选择了:{{selected}}</span>
</div>

结果:

使用v-for渲染动态选项

var test6=new Vue({
    el:'#test6',
    data:{
        selected:'A',
        options:[
            {text:'one',value:'A'},
            {text:'two',value:'B'},
            {text:'three',value:'C'}
        ]
    }
});
<div id="test6">
    <select v-model="selected">
        <option v-for="option in options" v-bind:value="option.value">
            {{option.text}}
        </option>
    </select>
    <span>{{selected}}</span>
</div>

结果:

Last modification:July 12th, 2020 at 01:08 am