我们接着上节文章 (Vue3 从入门到放弃 (第三篇.组件的使用)_Meta.Qing的博客-CSDN博客)
我们来实现props使用和注意事项.
Props 声明
在使用 的单文件组件中,props 可以使用 defineProps() 宏来声明
1.字符串数组来声明 props
- const props = defineProps(['foo'])
-
- console.log(props.foo)
2.对象实现props
- // 使用
- defineProps({
- title: String, //类型可以为String,Number,Function,Array,Boolean,Object
- likes: Number
- })
如果你正在搭配 TypeScript 使用 ,也可以使用类型标注来声明 props:
3 .使用 camelCase 形式,因为它们是合法的 JavaScript 标识符,可以直接在模板的表达式中使用,也可以避免在作为属性 key 名时必须加上引号
- defineProps({
- greetingMessage: String
- })
{{ greetingMessage }}
虽然理论上你也可以在向子组件传递 props 时使用 camelCase 形式 (使用 DOM 模板时例外),但实际上为了和 HTML attribute 对齐,我们通常会将其写为 kebab-case 形式:
<MyComponent greeting-message="hello" />
至此,你已经见过了很多像这样的静态值形式的 props:
<BlogPost title="My journey with Vue" />
应地,还有使用 v-bind 或缩写 : 来进行动态绑定的 props:
- <BlogPost :title="post.title" />
-
- <BlogPost :title="post.title + ' by ' + post.author.name" />
继续上节例子:
- // 声明一个props,默认值为default
- defineProps({
- titleHeader: {
- type: String,
- default: 'Meta.Qing'
- }
- })
-
-
- <template>
-
- <div class="meta-header">
-
- <div class="meta-header-logo">{{ titleHeader }} LOGOdiv>
- <nav>
-
- <a href="/HTML/">HTMLa> | <a href="/css/">CSSa> |
- <a href="/JavaScript/">JavaScripta> | <a href="/jQuery/">jQuerya> |
- <a href="/Vue3/">Vue3a> | <a href="/React/">Reacta> |
- <a href="/Angular/">Angulara>
- nav>
- div>
- template>
-
- <style scoped>
- /* 弹性盒子方式来布局 */
- .meta-header {
- display: flex;
- width: 100%;
- justify-content: space-between;
- background: #1fd6e766;
- padding: 10px;
- }
- .meta-header-logo {
- font-weight: bold;
- color: rgba(28, 29, 31, 0.804);
- }
- style>
