gpt4 book ai didi

javascript - 验证 vue.js 中的对象结构

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:57 25 4
gpt4 key购买 nike

我目前正在 vue.js 中构建一个组件,但遇到了一些问题。您看,您可以为我的组件提供很多参数,因此为了清楚起见,我决定采用以下方法:

<script type="text/javascript">
Vue.$noClientConf = {
'cmp_name': 'NoClient',
'cmp_title': 'Selection du client',
'url': 'ajax/getclients.php',
'parent': null,
'opt_texte': 'NomClientFR',
'opt_valeur': 'NoClient',
'cmp_max_options': 3,
'opt_custom': null,
'data_size': 10,
'data_style': 'btn btn-default btn-sm',
'data_live_search': 'true'
};
</script>

<div id="app">

<div class="col-lg-2">
<flex-select ref="NoClient" :conf="Vue.$noClientConf"></flex-select>
</div>

</div>

<script type="text/javascript">
var app = new Vue({
el: "#app",
data:{Vue}
});
</script>

基本上,我定义一个包含必要参数的对象,并将其提供给我的组件。问题是我想为其中一些参数定义一些默认值,以便用户不必列出所有参数。

现在,我已经阅读了有关 Vue.js Prop 验证的内容,并发现它非常适合我想做的事情。但是,虽然您可以验证 prop 是否是对象,但似乎无法验证对象的结构。例如,我希望能够做到:

props: {
config.cmp_name: {
type:String,
required: true
},
config.cmp_title:{
type:String,
required: true
}
}

所以我的问题基本上是......有没有办法做到以上?

最佳答案

使用object binding syntax .

<flex-select ref="NoClient" v-bind="defaults"></flex-select>

这将传递defaults所有属性,并仅验证您需要的属性。

props: {
cmp_name: {
type:String,
required: true
},
cmp_title:{
type:String,
required: true
}
}

否则,您可以使用函数作为 custom validator .

props:{
conf: {
validator(config){
let cmp_name = config.cmp_name && typeof config.cmp_name === "string"
let cmp_title = config.cmp_title && typeof config.cmp_title === "string"
return cmp_name && cmp_title
}
}
}

FWIW,我无法在示例中使 Vue.$noClientConf 正常工作。相反,我只是创建了一个默认对象。

console.clear()

const defaults = {
'cmp_name': 'NoClient',
'cmp_title': 'Selection du client',
'url': 'ajax/getclients.php',
'parent': null,
'opt_texte': 'NomClientFR',
'opt_valeur': 'NoClient',
'cmp_max_options': 3,
'opt_custom': null,
'data_size': 10,
'data_style': 'btn btn-default btn-sm',
'data_live_search': 'true'
};

Vue.component("flex-select",{
props: {
cmp_name: {
type:String,
required: true
},
cmp_title:{
type:String,
required: true
}
},
template:`
<div>{{cmp_name}} {{cmp_title}}</div>
`
})

new Vue({
el:"#app",
data:{
defaults
}
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<flex-select v-bind="defaults"></flex-select>
{{defaults}}
</div>

关于javascript - 验证 vue.js 中的对象结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com