VUE学习笔记十五:v-model,计算属性和侦听器
1.v-model数据双向绑定
<input v-model="searchText">
等价于:
<input
v-bind:value="searchText"
v-on:input="searchText = $event.target.value"
>
2.计算属性Computed (应用场景:代替其他字段)
<input type="text" v-model="inpNum"> //input只允许输入数字
computed:{
inpNum:{
get:function(){ //显示
return this.oldNum.replace(/[^\d]/g,'');
},
set:function(newValue){ //赋值
this.oldNum=newValue;
}
}
}
3.侦听器Watch (应用场景:监听联动属性,当前字段的变化自动改变关联字段)
watch:{//监听联动属性
firstName (val) {
this.fullName = val +' '+this.lastName
},
lastName (val) {
this.fullName = this.firstName + ' ' +val
},
question:function(newQuestion,oldQuestion){
this.answer = "Waiting for you to stop typing..."
this.debouncedGetAnswer()
}
}
4.自定义组件实例 (效果:input组件只允许输入数字,且将数字转成金额格式)
<template>
<input type="text" v-model="newValue" @blur="handleBlur" >
</template>
<script>
export default {
name:'dooneInput',
data(){
return {
// newValue:'',
oldNum:'',
}
},
props:{
value:{
type:Number,
default:''
}
},
methods:{
handleBlur($event){
var valueData = this.rmoney($event.target.value)
this.newValue = this.numberFormat(valueData)
this.$emit('input',valueData)
},
numberFormat(number, decimals, dec_point, thousands_sep) {
number = (number + '').replace(/[^0-9+-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 2 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function(n, prec) {
var k = Math.pow(10, prec);
return '' + Math.ceil(n * k) / k;
};
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
var re = /(-?\d+)(\d{3})/;
while(re.test(s[0])) {
s[0] = s[0].replace(re, "$1" + sep + "$2");
}
if((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
},
rmoney(e) {
if(isNaN(e)){
return parseFloat(e.replace(/[^\d\.-]/g, ""))
}else{
e=e?parseFloat(e):0;
return e;
}
},
},
computed:{
newValue:{
get(){
return this.oldNum.replace(/[^\d|,|\.]/g,'')
},
set(val){
this.oldNum = val
}
}
},
watch:{
value(newV,oldV){
//this.newValue = this.numberFormat(newV)
}
},
created(){
this.newValue = this.numberFormat(this.value)
}
}
</script>
<style lang="scss">
</style>
文章
总共 0 条评论