ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 定义属性并获取属性值 定义属性我们需要用props选项,加上数组形式的属性名称,例如:props:[‘here’]。在组件的模板里读出属性值只需要用插值的形式,例如{{ here }}. ~~~javascript <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="../assets/js/vue.js"></script> <title>component-2</title> </head> <body> <h1>component-2</h1> <hr> <div id="app"> <panda here="China"></panda> </div> <script type="text/javascript"> var app=new Vue({ el:'#app', components:{ "panda":{ template:`<div style="color:red;">Panda from {{ here }}.</div>`, props:['here'] } } }) </script> </body> </html> ~~~ 上面的代码定义了 panda 的组件,并用 props 设置了 here 的属性值,在 here 属性值里传递了China 给组件。 最后输出的结果是红色字体的 Panda from China. ## 属性中带’-‘的处理方式 我们在写属性时经常会加入’-‘来进行分词,比如:`<panda from-here=”China”></panda>`,那这时我们在props里如果写成`props:[‘form-here’]`是错误的,我们必须用小驼峰式写法`props:[‘formHere’]`。 ~~~javascript <panda from-here="China"></panda> var app=new Vue({ el:'#app', components:{ "panda":{ template:`<div style="color:red;">Panda from {{ here }}.</div>`, props:['fromHere'] } } }) ~~~ PS:因为这里有坑,所以还是少用-为好。 ### 在构造器里向组件中传值 把构造器中data的值传递给组件,我们只要进行绑定就可以了。就是我们第一季学的v-bind:xxx. 我们直接看代码: ~~~javascript <panda v-bind:here="message"></panda> var app=new Vue({ el:'#app', data:{ message:'SiChuan' }, components:{ "panda":{ template:`<div style="color:red;">Panda from {{ here }}.</div>`, props:['here'] } } }) ~~~