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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM