Vue组件注册命名方式(驼峰和短横线)

定义组件名的方式有两种:

1.使用 kebab-case

Vue.component('my-component-name', { /* ... */ })

当使用 kebab-case (短横线分隔命名) 定义一个组件时,你也必须在引用这个自定义元素时使用 kebab-case,例如 <my-component-name>

2.使用 PascalCase

Vue.component('MyComponentName', { /* ... */ })

当使用 PascalCase (首字母大写命名) 定义一个组件时,你在引用这个自定义元素时两种命名法都可以使用。也就是说 <my-component-name> 和 <MyComponentName> 都是可接受的。注意,尽管如此,直接在 DOM (即非字符串的模板) 中使用时只有 kebab-case 是有效的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <!-- 在普通的标签模板中,推荐使用短横线的方式使用组件 -->
        <hello-world></hello-world>
        <p>---------------这里是分割线---------------</p>
        <button-counter></button-counter>
    </div>
    <script type="text/javascript" src="./vue.js"></script>
    <script type="text/javascript">
        /*
            组件命名方式: 短横线、驼峰
            Vue.component('my-component', {})
            Vue.component('MyComponent', {})
            如果使用驼峰式命名组件,那么在使用组件的时候,只能在字符串模板中用驼峰的方式使用组件,但是在普通的标签模板中,必须使用短横线的方式使用组件
        */
        Vue.component('HelloWorld', {
            template: '<div>{{msg}} --- 哈哈哈</div>',
            data() {
                return {
                    msg: 'HelloWorld'
                }
            }
        });
        Vue.component('button-counter', {
            template: `
                <div>
                    <button @click="handle">点击了{{count}}次</button>
                    <button>测试123</button>
                    <!-- 在字符串模板中用驼峰的方式使用组件 -->
                    <h3>下面是在字符串模板中用驼峰的方式使用组件</h3>
                    <HelloWorld></HelloWorld>
                </div>
            `,
            data() {
                return {
                    count: 0
                }
            },
            methods: {
                handle: function () {
                    this.count += 2;
                }
            }
        })
        var vm = new Vue({
            el: '#app',
            data: {}
        });
    </script>
</body>
</html>

 参考:https://cn.vuejs.org/v2/guide/components-registration.html

posted @ 2020-12-10 17:08  盼星星盼太阳  阅读(1559)  评论(0)    收藏  举报