- 使用watch方法
<template>
<div class="box">
<textarea v-model="title" width="100%" ></textarea>
<span>还可以输入{{this.titleMaxLength - this.title.length}}</span>
</div>
</template>
<script>
export default {
name: 'Box',
data() {
return {
title: '',
titleMaxLength: 60
};
},
methods:{
},
watch: {
title() {
if (this.title.length > this.titleMaxLength) {
this.title = String(this.title).slice(0, this.titleMaxLength);
}
}
}
}
</script>
<style lang="less">
.box{
width: 100%;
textarea{
width: 100%;
height: 60px;
border: none;
outline: none;
box-sizing: border-box;
}
}
</style>
- 自定义指令
- 组件内注册
<template>
<div class="box">
<textarea v-sliceString="titleMaxLength" v-model="title" width="100%" ></textarea>
<span>还可以输入{{this.titleMaxLength - this.title.length >= 0 ?this.titleMaxLength - this.title.length : 0 }}</span>
</div>
</template>
<script>
export default {
name: 'Box',
data() {
return {
title: '',
titleMaxLength: 10,
};
},
methods:{
},
directives: {
sliceString: {
update(el, binding) {
if (el.value.length >= binding.value) {
el.value = el.value.slice(0, binding.value);
}
}
}
}
}
</script>
<style lang="less">
.box{
width: 100%;
textarea{
width: 100%;
height: 60px;
border: none;
outline: none;
box-sizing: border-box;
}
}
</style>
全局注册
// man.js
Vue.directive('limitTextLen', {
bind: function () {},
inserted: function () {},
update: function (el, binding) {
if (el.value.length >= binding.value) {
el.value = el.value.slice(0, binding.value);
}
},
componentUpdated: function () {},
unbind: function () {}
});
网友评论