Vue - 驼峰和短横线分割命名注意事项

文章详细介绍了在Vue中组件注册、父子组件间的数据传递和函数传递时,驼峰命名(PascalCase)和短横线命名(kebab-case)的使用规则。组件注册通常使用PascalCase,而在模板中引用时两者均可。父子组件间,数据传递从父到子时,父组件用kebab-case,子组件需用驼峰命名接收。函数传递则无特殊要求,原名传递即可。
摘要由CSDN通过智能技术生成

一. 驼峰和短横线分割命名注意事项

我们一般定义组件的方式有两种:

  • 短横线分隔命名:kebab-case
  • 首字母大写命名:PascalCase

1.1 组件注册命名

例如,我写一个简单的子组件。

<template>
  <div class="border">
    <h2>我是子组件</h2>
  </div>
</template>

<script setup>

</script>
<style scoped>
.border {
  border: 1px solid;
  width: 400px;
}
</style>

注册的时候采用PascalCase命名:

createApp(App)
    .component('MyComponent', MyComponent)
    .mount('#app')

使用的时候:

<template>
  <div class="border">
    <h1 >我是父组件</h1>
    <my-component />
    <!-- <MyComponent /> -->
    <!-- <myComponent /> -->
  </div>
</template>

<style scoped>
.border {
  border: 1px solid;
  width: 400px;
  height: 200px;
}
</style>

结果如下:
在这里插入图片描述

自定义的组件在使用上,命名的规则如下:

  • 注册的时候:使用了PascalCase命名。
  • 使用的时候:可以使用PascalCase命名(首字母不区分大小写)或者kebab-case命名(每个单词的首字母不区分大小写)。

一般编码的时候,习惯这样:命名的时候采取PascalCase命名法,使用的时候采取kebab-case法(每个单词的首字母小写)。

1.2 父子组件数据传递时命名

父组件在给子组件传递变量的时候,如果变量名称采用kebab-case法,那么子组件在接收的时候应该写驼峰命名法。

例如,我再父组件中这么传参:

<MyComponent :user-name="name"/>

子组件的接收:驼峰命名法。

<template>
  <div class="border">
    <h2>我是子组件</h2>
    <div>接收来自父组件传入的参数:{{ props.userName }}</div>
  </div>
</template>

<script setup lang="ts">
import { computed, defineProps, withDefaults } from "vue";

interface Props {
  // 记得使用驼峰命名法
  userName: string;
}
const props = withDefaults(defineProps<Props>(), {
  userName: "",
});

</script>
<style scoped>
.border {
  border: 1px solid;
  width: 400px;
}
</style>

效果如下:
在这里插入图片描述

1.3 父子组件函数传递

父组件在传递给子组件的时候,命名上我测试下来没有什么特殊的要求。先说下传递的命名上:

父组件传递:

<MyComponent :user-name="name" @sayHello="sayHello"/>

const sayHello =  ()=>{
  console.log('Hello')
}

子组件的接收上:

<template>
  <div class="border">
    <h2>我是子组件</h2>
    <div>接收来自父组件传入的参数:{{ props.userName }}</div>
    <a @click="hello">点击</a>
    <br>
    <a @click="hello2">点击2</a>
  </div>
</template>

<script setup lang="ts">
import { defineProps, withDefaults } from "vue";

interface Props {
  userName: string;
}
const props = withDefaults(defineProps<Props>(), {
  userName: "",
});

const emit = defineEmits(["say-hello", "sayHello"]);
const hello = () => {
  emit("say-hello");
};
const hello2 = () => {
  emit("sayHello");
};
</script>
<style scoped>
.border {
  border: 1px solid;
  width: 400px;
}
</style>

结果如下:无论是使用下划线分割还是原名,都可以正常接收。
在这里插入图片描述
经过测试,父组件在传函数的时候,使用kebab-case法,和上述案例一个效果。

因此我们就这么约定吧:

  • 父组件传递函数的时候,就原名传入即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zong_0915

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值