一、 组件
1. 非单文件组件
Vue 使用组件的三大步骤:
创建组件
使用 Vue.extend(options) 创建组件
注意:
- el 不好写
- data 必须写成函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const student = Vue.extend({ template:` <div> <h2>学生姓名:{{studentName}}</h2> <h2>学生年龄:{{age}}</h2> </div> `, data(){ return { studentName:'张三', age:18 } } })
|
注册组件
- 局部注册:靠new Vue的时候传入components选项
- 全局注册:靠Vue.component(‘组件名’,组件)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| Vue.component('hello',hello)
new Vue({ el:'#root', data:{ msg:'你好啊!' }, components:{ student } })
|
使用组件
1 2 3 4
| <div id="root"> <student></student> </div>
|
关于组件名:
- 一个单词组成:
- 第一种写法(首字母小写):school
- 第二种写法(首字母大写):School
- 多个单词组成:
- 第一种写法(kebab-case命名):my-school
- 第二种写法(CamelCase命名):MySchool (需要Vue脚手架支持)
备注:
可以使用 name
配置项指定组件在开发者工具中呈现的名字。
关于组件标签:
- 第一种写法:
- 第二种写法:
备注:不用使用脚手架时,会导致后续组件不能渲染。
一个简写方式:
const school = Vue.extend(options) 可简写为:const school = options
::: details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>组件的嵌套</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="root"> </div> </body>
<script type="text/javascript"> Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//定义student组件 const student = Vue.extend({ name:'student', template:` <div> <h2>学生姓名:{{name}}</h2> <h2>学生年龄:{{age}}</h2> </div> `, data(){ return { name:'尚硅谷', age:18 } } }) //定义school组件 const school = Vue.extend({ name:'school', template:` <div> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <student></student> </div> `, data(){ return { name:'尚硅谷', address:'北京' } }, //注册组件(局部) components:{ student } })
//定义hello组件 const hello = Vue.extend({ template:`<h1>{{msg}}</h1>`, data(){ return { msg:'欢迎来到尚硅谷学习!' } } }) //定义app组件 const app = Vue.extend({ template:` <div> <hello></hello> <school></school> </div> `, components:{ school, hello } })
//创建vm new Vue({ template:'<app></app>', el:'#root', //注册组件(局部) components:{app} }) </script> </html>
|
:::
2. 单文件组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <template> <div> <h2>学生姓名:{{name}}</h2> <h2>学生年龄:{{age}}</h2> </div> </template> <script> export default { name:'Student', data(){ return { name:'张三', age:18 } } } </script>
|
</code-block>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <template> <div> <Student></Student> </div> </template>
<script> //引入组件 import Student from './Student.vue'
export default { name:'App', components:{ Student } } </script>
|
</code-block>
1 2 3 4 5 6 7
| import App from './App.vue'
new Vue({ el:'#root', template:`<App></App>`, components:{App}, })
|
</code-block>
1 2 3 4 5 6 7 8 9 10 11
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>练习一下单文件组件的语法</title> </head> <body> <div id="root"></div> </body> </html>
|
</code-block>
</code-group>