vue组件的驼峰式命名与短横线分割命名

起因是因为看见下图,自己没明白为什么,从而上网查了一下。

参考:https://blog.csdn.net/qq_43650979/article/details/105839130

官网给出说明为:

1.注册组件的时候使用了驼峰命名
如果在注册组件的时候使用了驼峰命名, 那么在使用时需要转换成短横线分隔命名

 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     <my-son></my-son><!-- 使用时:短横线分割命名-->
11 </div>
12 <template id="son">
13     <div>
14         <p>......</p>
15     </div>
16 </template>
17 <script>
18     Vue.component("mySon", { // 注册时:驼峰式命名
19         template: "#son",
20     });
21     let vue = new Vue({
22         el: '#app',
23     });
24 </script>
25 </body>
26 </html>
2.传递数据时使用驼峰名称
如果父组件向子组件传递数据时使用了短横线分隔命名, 子组件接收时写驼峰式命名

 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     <my-son :parent-name="name"></my-son><!-- 向子组件传递数据:短横线分割命名,不能使用驼峰式-->
11 </div>
12 <template id="son">
13     <div>
14         <p>{{parentName}}</p><!-- 驼峰式使用-->
15     </div>
16 </template>
17 <script>
18     Vue.component("mySon", {
19         template: "#son",
20         props:["parentName"] // 驼峰式接收
21     });
22     let vue = new Vue({
23         el: '#app',
24         data:{
25             name:"test"
26         }
27     });
28 </script>
29 </body>
30 </html>
View Code
3.传递方法时双方都不能使用驼峰命名, 只能用短横线分隔命名

 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     <my-son :parent-name="name" @parent-fn="fn"></my-son><!-- 向子组件传递方法:短横线分割命名,不能使用驼峰式-->
11 </div>
12 <template id="son">
13     <div>
14         <button @click="fn">按钮</button>
15         <p>{{parentName}}</p>
16     </div>
17 </template>
18 <script>
19     Vue.component("mySon", {
20         template: "#son",
21         props:["parentName"],
22         methods:{
23             fn(){
24                 this.$emit("parent-fn"); // 短横线式接收
25             }
26         }
27     });
28     let vue = new Vue({
29         el: '#app',
30         data:{
31             name:"test1"
32         },
33         methods:{
34             fn(){
35                 console.log("test2");
36             }
37         }
38     });
39 </script>
40 </body>
41 </html>
View Code
原文地址:https://www.cnblogs.com/cjll/p/13706747.html