Vue中表单数据和过滤器
表单数据
案例演示
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="../js/vue.js">script>
head>
<body>
<div id="context">
<form @submit.prevent="demo">
账号:<input type="text" v-model.trim="userInfo.account"> <br/><br/>
密码:<input type="password" v-model="userInfo.password"> <br/><br/>
年龄:<input type="number" v-model.number="userInfo.age"> <br/><br/>
性别:
男<input type="radio" name="sex" v-model="userInfo.sex" value="male">
女<input type="radio" name="sex" v-model="userInfo.sex" value="female"> <br/><br/>
爱好:
学习<input type="checkbox" v-model="userInfo.hobby" value="study">
打游戏<input type="checkbox" v-model="userInfo.hobby" value="game">
吃饭<input type="checkbox" v-model="userInfo.hobby" value="eat">
<br/><br/>
所在地区
<select v-model="userInfo.city">
<option value="">请选择地区option>
<option value="beijing">北京option>
<option value="shanghai">上海option>
<option value="shenzhen">深圳option>
select>
<br/><br/>
其他信息:
<textarea v-model.lazy="userInfo.other">textarea> <br/><br/>
<input type="checkbox" v-model="userInfo.agree">阅读并接受<a href="http://www.baidu.com">《用户协议》a>
<button>提交button>
form>
div>
body>
<script type="text/javascript">
new Vue({
el:'#context',
data:{
userInfo:{
account:'',
password:'',
age:18,
sex:'female',
hobby:[],
city:'beijing',
other:'',
agree:''
}
},
methods: {
demo(){
console.log(JSON.stringify(this.userInfo))
}
}
})
script>
html>
备注
过滤器
- 定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)。
- 语法:
- 注册过滤器:
Vue.filter(name,callback)
或 new Vue{filters:{}}
- 使用过滤器:
{{ xxx | 过滤器名}}
或 v-bind:属性 = "xxx | 过滤器名"
- 备注:
- 过滤器也可以接收额外参数、多个过滤器也可以串联
- 并没有改变原本的数据, 是产生新的对应的数据
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="../js/vue.js">script>
head>
<body>
<div id="context">
<h2>{{msg | toSlice}}h2>
<h2 v-bind:aaa="msg | toSlice">h2>
<h2>{{msg | toSlice | secondSlice}}h2>
<h2>{{msg | toSliceWithParam(5)}}h2>
div>
body>
<script type="text/javascript">
new Vue({
el: '#context',
data: {
msg: '你好,machoul'
},
filters: {
toSlice(val) {
return val.slice(0, 4)
},
toSliceWithParam(val, number) {
return val.slice(0, number)
},
secondSlice(val) {
return val.slice(0, 2)
}
}
})
script>
html>