iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >Vue驼峰与短横线分割命名中有哪些坑
  • 762
分享到

Vue驼峰与短横线分割命名中有哪些坑

Vue驼峰Vue短横线分割命名 2023-02-10 12:02:34 762人浏览 安东尼
摘要

目录驼峰和短横线分割命名注意事项组件注册命名父子组件数据传递时命名父子组件函数传递驼峰和短横线分割命名注意事项 我们一般定义组件的方式有两种: 短横线分隔命名:kebab-case。

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

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

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

组件注册命名

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

<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法(每个单词的首字母小写)。

父子组件数据传递时命名

父组件在给子组件传递变量的时候,如果变量名称采用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>

效果如下:

父子组件函数传递

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

父组件传递:

<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法,和上述案例一个效果。

因此我们就这么约定吧:

父组件传递函数的时候,就原名传入即可。

到此这篇关于Vue驼峰与短横线分割命名中有哪些坑的文章就介绍到这了,更多相关Vue驼峰与短横线分割命名内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Vue驼峰与短横线分割命名中有哪些坑

本文链接: https://www.lsjlt.com/news/195532.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作