08.表单数据绑定

goer ... 2022-01-06 Vue
  • Javascript
  • Vue
小于 1 分钟

表单

# 表单数据绑定

v-model 指令在表单<input><textarea><select> 元素上创建双向数据绑定。

// input textarea
<input type="text" placeholder="input" v-model="inputMsg">
<p>input: {{inputMsg}}</p>
<hr>
<textarea v-model="textMsg" name="text" id="" cols="30" rows="10" placeholder="text">
</textarea>
<p>textmsg: {{textMsg}}</p>
<hr>

data(){
    return{
        inputMsg:'',
        textMsg:'',
    }
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// radio  checkbox

<input v-model="msgSex" type="radio" name="sex" value=""><input v-model="msgSex" type="radio" name="sex" value=""><input v-model="msgSex" type="radio" name="sex" value="保密"> 保密

<p>this sex : {{msgSex}}</p>
<hr>

<input v-model="loves" type="checkbox" name="love" id="" value="篮球">篮球
<input v-model="loves" type="checkbox" name="love" value="足球"> 足球
<input v-model="loves" type="checkbox" name="love" value="跑步"> 跑步
<input v-model="loves" type="checkbox" name="love" value="洗澡" id="">洗澡
<p>this love: {{loves}}</p>
<hr>

data(){
    return{
        msgSex:'',
        loves:[],  //注意
    }
},

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

多选框: 默认是数组

<select v-model="sex2">
    <option value="" disabled>选择性别</option>
    <option value=""></option>
    <option value=""></option>
</select>
<p>this sex: {{sex2}}</p>

data{
	sex2:'',
} 
1
2
3
4
5
6
7
8
9
10

提交数据 重点


<input type="submit" value="login" v-on:click="datalogin">

        const app = new Vue({
          el:'#app',
          data(){
            return{
              inputMsg:'',
              textMsg:'',
              msgSex:'',
              loves:[],
              sex2:'',
            }
          },
          methods:{
            sublogin: function(){
              console.log(this.inputMsg);
              var formdata = {
                msg1:this.inputMsg,
                msg2:this.textMsg,
                msg3:this.msgSex,
                msg4:this.loves,
                msg5:this.sex2,
              };
              console.log(formdata);
            }
          }
        })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

这样绑定数据,就可以提交了