今天学习props验证,用了一个例子,感觉代码没什么错误,控制台也没有报错,可是程序就是不运行 。
父组件调用部分代码如下:
<div id="app"> <poetry-comp :poemArr="poemList" :num="poemList.length"></poetry-comp></div>
子组件模板部分代码如下:
<ul> <li v-for="item in poemArr" :key="item.id"><h3>{{item.id}}.{{item.title}}</h3> <h4>{{item.author}}</h4><p>{{item.content}}</p></li>
</ul>
script代码部分如下:
const PoetryComp = { template:'#tp_child',props:{poemArr:Array, //poemArr类型是数组, }
}
后来到官网查看了一下,《传递 prop 的细节》小节中提到,“Prop 名字格式”,如果一个 prop 的名字很长,应使用 camelCase 形式,即驼峰命名法。可以直接在模板的表达式中使用,如下:
<span>{{ poemArr }}</span>
结论
虽然理论上也可以在向子组件传递 props 时使用 camelCase 形式 (使用 DOM 内模板时例外),但实际上为了和 HTML attribute 对齐,我们通常会将其写为 kebab-case 形式,即短横线形式。也就是说,在我用的例子中,父组件调用时,把poemArr 改成poem-arr,然后就正常运行了。
<div id="app"> <poetry-comp :poem-arr="poemList" :num="poemList.length"></poetry-comp></div>
完整代码如下:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta title="viewport" content="width=device-width, initial-scale=1.0"><title>Props对组件传递的数据进行验证</title><script src="https://unpkg.com/vue@3/dist/vue.global.js"></script></head><body> <div id="app"> <!--调用 PoetryComp 组件 :poem-arr短横线命名法,对接后面的poemArr--> <poetry-comp :poem-arr="poemList" :num="poemList.length"></poetry-comp></div> <template id="tp_child"> <!--PoetryComp 子组件模板结构 v-for指令循环输出--> <div> <h3>诗集中共{{num}}首诗</h3> <ul> <li v-for="item in poemArr" :key="item.id"><h3>{{item.id}}.{{item.title}}</h3> <h4>{{item.author}}</h4><p>{{item.content}}</p></li></ul> </div> </template> </body> <script>const RootComponent = { data(){ return{ poemList:[{id:1,title:'登鹳雀楼 ',author:'唐·王之涣',content:'欲穷千里目,更上一层楼。'},{id:2,title:'江上',author:'宋·王安石',content:'青山缭绕疑无路,忽见千帆隐映来。'},{id:3,title:'秋词',author:'唐·刘禹锡',content:'古人逢秋悲寂寥,我言秋日胜春朝。'} ],} } }const PoetryComp = { //创建子组件template:'#tp_child',props:{poemArr:Array, //poemArr类型是数组,num:{type: Number, //类型为Number validator(value) { //验证函数,当前数组元素为3个,验证不通过 return value>0 && value<3} }, } } const appObj = Vue.createApp(RootComponent)appObj.component('PoetryComp',PoetryComp) //组件全局注册appObj.mount("#app")</script>
</html>