1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>组件的创建注册和使用</title>
    6. <script src="../js/vue.js"></script>
    7. </head>
    8. <body>
    9. <div id="app">
    10. <h1>{{msg}}</h1>
    11. <!-- 3.使用组件 -->
    12. <userlist></userlist>
    13. <userlist></userlist>
    14. <userlogin></userlogin>
    15. <userlogin></userlogin>
    16. </div>
    17. <script>
    18. // 1.创建组件
    19. const userListComponent = Vue.extend({
    20. template : `
    21. <ul>
    22. <li v-for="(user,index) of users" :key="user.id">
    23. {{index}},{{user.name}}
    24. </li>
    25. </ul>
    26. `,
    27. data(){
    28. return {
    29. users : [
    30. {id:'001', name:'jack'},
    31. {id:'002', name:'lucy'},
    32. {id:'003', name:'james'}
    33. ]
    34. }
    35. }
    36. })
    37. // 1.创建组件
    38. const userLoginComponent = Vue.extend({
    39. template : `
    40. <div>
    41. <h3>用户登录</h3>
    42. <form @submit.prevent="login">
    43. 账号:<input type="text" v-model="username"><br><br>
    44. 密码:<input type="password" v-model="password"><br><br>
    45. <button>登录</button>
    46. </form>
    47. </div>
    48. `,
    49. data(){
    50. return {
    51. username : 'admin',
    52. password : '123'
    53. }
    54. },
    55. methods : {
    56. login(){
    57. alert(this.username + "," + this.password)
    58. }
    59. }
    60. })
    61. const vm = new Vue({
    62. el : '#app',
    63. data : {
    64. msg : '组件的创建注册和使用'
    65. },
    66. // 2.注册组件(局部注册)
    67. components : {
    68. // userlist 就是组件的名字
    69. userlist : userListComponent,
    70. userlogin : userLoginComponent
    71. }
    72. })
    73. </script>
    74. </body>
    75. </html>

    (1) 创建组件
    1 const userComponent = Vue.extend({这个配置项和创建 Vue 实例的配置项几乎是一样的,只是略有差异})
    2 需要注意的是:
    1) el 不能用。组件具有通用性,不特定为某个容器服务,它为所有容器服务。
    2) data 必须使用函数形式:return {}
    3) 使用 template 配置项配置页面结构:HTML。
    (2) 注册组件
    1 局部注册
    1) 使用 components 配置项:components : {user : userComponent},user 就是组件名。
    2 全局注册
    1) Vue.component(‘user’, userComponent)
    (3) 使用组件
    1 直接在页面需要使用组件的位置:
    2 也可以这样使用: (不在脚手架环境中使用这种方式会出现后续元素不渲染的问题。)
    (4) 创建组件对象也有简写形式:Vue.extend() 可以省略。直接写:{}
    (5) 组件的命名细节:
    1 全部小写
    2 首字母大写,后面全部小写
    3 kebab-case 串式命名法
    4 CamelCase 驼峰式命名法(这种方式需要在脚手架环境中使用)
    5 不要使用 HTML 内置的标签作为组件名称。
    6 可以使用 name 配置项来指定 Vue 开发者工具中显示的组件名。