- 阐述
- 准备基本文件
- 对类型的校验
- 必填校验和默认值设置
- required 必填项
- default 默认值
- 精准校验 validator
现在你已经可以轻松的给组件进行传值了,用起来很方便和自由,在实际开发中,这些传递的参数也很可能是通过用户的输入而获得的,必要的前端验证是必不可少的。
但是在组件中也需要作最基本的验证。
本节我们就一起来学习一下Vue3中组件传值的验证。
准备基本文件DOCTYPE html>
Demo27
const app = Vue.createApp({
data() {
return {
name: 123
}
},
template: `
willem.com
`
})
app.component('Son',{
props:['name'],
template:`{{ typeof name}} div `
})
const vm = app.mount("#app")
对类型的校验
有时候我们希望传递过来的属性是一个字符串,但很可能用户传递过来的就是一个数字,这时候我希望程序能给我一个提示,让我能做一些业务逻辑处理。
这就涉及到了对参数类型的判断。
app.component('Son', {
props: {
name: String
},
template: `{{name}} div `
})
这时候代码就有了校验功能,打开控制台 Console
就可以看到提示。 这里需要注意的是,这种提示不会报错和阻断程序,只是会在控制台给出warn
警告信息。
这时候把数据项中的
123
,修改为字符串 '123'
时,程序就不再报错了。
Vue支持的校验类型包括:String、Boolean、Array、Object、Function和Symbol
。
DOCTYPE html>
Demo27
const app = Vue.createApp({
data() {
return {
name: 123
}
},
template: `
willem.com
`
})
app.component('Son', {
props: {
name: String
},
template: `{{name}} div `
})
const vm = app.mount("#app")
有些参数是必须要传递的,但有些参数就是可以不传的,当不传时。 我们只要给系统一个默认值就可以了。 所以有必要对这两个知识学习一下。
required 必填项如果要求组件使用时,必须传递参数,可以使用 required
来校验.
app.component('Son', {
props: {
name: {
type: String,
required: true
}
},
template: `{{name}} div `
})
这时候的校验规则就是,name
的值必须是字符串,并且不可以省略。 这时候可以去掉父组件调用时传递的参数。
template: `
willem.com
`
在浏览器中打开控制台看一下警告信息。
再来看一下默认值的写法,在原来写 required
的地方直接写 default
就可以了。
比如写成下面的样子。
app.component('Son', {
props: {
name: {
type: String,
default: 'Son willem.com'
}
},
template: `{{name}} div `
})
这时候的意思就是在调用 Son
组件时,如果不传递参数,则默认值为 Son willem.com div。
template: `
willem.com
`
DOCTYPE html>
Demo27
const app = Vue.createApp({
data() {
return {
name: 123
}
},
template: `
willem.com
`
})
app.component('Son', {
props: {
name: {
type: String,
default: 'Son willem.com'
}
},
template: `{{name}} div `
})
const vm = app.mount("#app")
精准校验 validator
如果上面这些校验都不能满足你的要求,还可以进行精准校验。
比如现在要求传递的字符串中必须包括 willembj123
这几个字符,就可以用 validator
来进行校验。
它是一个函数,并接受一个value
值,这个value
就是传递过来的值。
app.component('Son', {
props: {
name: {
type: String,
validator: function (value) {
console.log(value.search("willembj123 "))
return value.search("willembj123 ") != -1
},
default: 'willembj123.com'
}
},
template: `{{name}} div `
})
因为使用 search
来验证,返回来的是字符串出现的位置,没有找到时才显示 -1
。所以这里判定如果不为 -1
就是通过验证。
当没有通过验证时,就是在控制台给出警告。
以上就是关于Vue组件传值时的校验操作的所有内容了,希望通过学习你可以知道组件传值时的验证方法。
DOCTYPE html>
Demo27
const app = Vue.createApp({
data() {
return {
name: 123
}
},
template: `
willem.com
`
})
app.component('Son', {
props: {
name: {
type: String,
validator: function (value) {
console.log(value.search("willembj123 "))
return value.search("willembj123 ") != -1
},
default: 'willembj123.com'
}
},
template: `{{name}} div `
})
const vm = app.mount("#app")