props_3">1 组件的 props
为了提高组件的复用性,在封装 vue 组件时需要遵守如下的原则:
为了方便使用者为组件提供要展示的数据,vue 组件提供了 props 的概念。
props 是组件的自定义属性,组件的使用者可以通过 props 把数据传递到子组件内部,供子组件内部进行使用。
props 的作用:
父组件通过 props 向子组件传递要展示的数据。
props_18">2 在组件中声明 props
在封装 vue 组件时,可以把动态的数据项声明为 props 自定义属性。自定义属性可以在当前组件的模板结构中被直接使用。示例代码如下:
<template>
<div>
<h3>标题:{{title}}</h3>
<h5>作者:{{author}}</h5>
<h6>发布时间:{{pubTime}}</h6>
</div>
</template>
<script>
export default {
name: 'MyArticle',
// 外界可以传递指定的数据,到当前的组件中
props: ['title', 'author', 'pubTime']
}
</script>
可以使用 v-bind 属性绑定的形式,为组件动态绑定 props 的值。
<template>
<div>
<h1>这是 App.vue 根组件</h1>
<hr />
<my-article :title="info.title" :author="'post by ' + info.author" pub-time="1989"></my-article>
</div>
</template>
<script>
import MyArticle from './Article.vue'
export default {
name: 'MyApp',
data() {
return {
info: {
title: 'abc',
author: '123',
},
}
},
components: {
MyArticle,
},
}
</script>
props_74">3 无法使用未声明的 props
如果父组件给子组件传递了未声明的 props 属性,则这些属性会被忽略,无法被子组件使用,示例代码如下:
<template>
<div>
<h3>标题:{{title}}</h3>
<h5>作者:{{author}}</h5>
<h6>发布时间:{{pubTime}}</h6>
</div>
</template>
<script>
export default {
name: 'MyArticle',
// 外界可以传递指定的数据,到当前的组件中
props: ['title', 'author']
}
</script>
<template>
<div>
<h1>这是 App.vue 根组件</h1>
<hr />
<my-article :title="info.title" :author="'post by ' + info.author" pub-time="1989"></my-article>
</div>
</template>
<script>
import MyArticle from './Article.vue'
export default {
name: 'MyApp',
data() {
return {
info: {
title: 'abc',
author: '123',
},
}
},
components: {
MyArticle,
},
}
</script>
在子组件中不存在pubTime。
props__126">4 props 的大小写命名
组件中如果使用“camelCase (驼峰命名法)”声明了 props 属性的名称,则有两种方式为其绑定属性的值:
<template>
<div>
<h6>发布时间:{{pubTime}}</h6>
</div>
</template>
<script>
export default {
name: 'MyArticle',
// 外界可以传递指定的数据,到当前的组件中
props: ['pubTime']
}
</script>
<template>
<div>
<h1>这是 App.vue 根组件</h1>
<hr />
<my-article pub-time="1989"></my-article>
<my-article pubTime="1989"></my-article>
</div>
</template>
<script>
import MyArticle from './Article.vue'
export default {
name: 'MyApp',
data() {
return {
info: {
title: 'abc',
author: '123',
},
}
},
components: {
MyArticle,
},
}
</script>