vue 组件-自定义组件4种方式

一、组件命名的方式

  ①kebab-case,单词之间采用  - (短横线)连接,例如:my-component ,在DOM中使用时,<my-component ></my-component >

  ②PascalCase,驼峰式名称,单词之间,首字母大写,例如:MyComponent,但是在DOM中使用时,必须更改为,<my-component ></my-component >,<MyComponent></MyComponent>是识别不了的。

 

二、全局注册

①通过Vue.extend()和Vue.component()注册

// 方式1
    var tmp1 = Vue.extend({
        template: "<p>通过 Vue.extend 创建的 tmp1 组件</p>"
    });
    Vue.component("tmp1", tmp1);


    // 方式2
    Vue.component("tmp2", Vue.extend({
        template: "<p>通过 Vue.extend 创建的 tmp2 组件</p>"
    }));

②通过Vue.component()字面量注册

     Vue.component("tmp3", {
        template: "<h3>通过字面量方式创建的tmp3组件</h3>"
     });

③通过<template id="tmp1"> 方式注册

js部分:

Vue.component("tmp4", {
         template: "#template1"
     });

HTML部分:

<template id="template1">
   <h4>这是通过 app 外部 template 标签自定义的 tmp4 组件</h4>
</template>

三、定义局部组件

局部组件定义在vue实例内部,该组件只能在vue实例控制范围内才能使用

JS部分:

var app2 = new Vue({
        el: "#app2",
        components: {
            "temp5": {
                template: "<h1>app2 的局部组件 h1 </h1>"
            },
            "temp6":{
                template:"<h2>app2 的局部组件 h2 </h2>"
            }
        }
    });

HTML部分:

<div id="app">
        <!-- 在这里使用app2注册的局部组件会报错 -->
        <!-- <temp5></temp5> -->
    </div>

    <div id="app2">
        <temp5></temp5>
    </div>

在app中使用了temp5组件会报以下警告:

 [Vue warn]: Unknown custom element: <temp5> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

错误原因:
HTML 中的标签名是大小写不敏感的,所以浏览器会把所有大写字符解释为小写字符。这意味着当你使用 DOM 中的模板时,使用驼峰命名法 的 prop 名需要使用其等价的短横线分隔命名方法或者全部使用小写。否者就会报上述错误。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值