
3-Vue头像组件
组件
建立文件
文件目录
- components
- Avatar.vue
- 其他组件
- components
文件结构
可下载
vscode
组件:vetur
可识别
vue
代码提供了常用的代码片段
default.vue
: 生成vue
结构1
2
3
4
5
6
7
8
9
10
11
12
13<template>
</template>
<script>
export default {
}
</script>
<style>
</style>
配置组件
填写组件
1
2
3
4
5
6
7
8
9
10
11
12
13<template>
<img :src="url"/>
</template>
<script>
export default {
props: ["url"],
}
</script>
<style>
</style>在
App.vue
中使用组件1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<template>
<div>
<h1>App组件</h1>
<Avatar url="https://xn--zsr428b1mg.com/image/blog-avatar.jpg"/>
</div>
</template>
<script>
import Avatar from "./component/Avatar" // .vue后缀可以省略
export default {
components: {
Avatar
}
}
</script>
<style>
</style>
组件传参
传参:
- 传递字符串
1
<Avatar url="1" />
- 非字符串在传参前添加
:
, 此时""
内不再是字符串, 而是Js
表达式, 如果以这种形式仍想传入字符串则可使用单引号包裹1
2<Avatar :url="1" />
<Avatar :url="'1'" />
- 传递字符串
声明属性
v-bind缩写:
:
数组
数组的每一项都是一个属性对象
属性名: 属性类型
的形式, 为属性添加约束1
2
3props: {
url: String,
},还可以进一步限定是否必须传递
1
2
3
4
5
6props: {
url: {
type: String,
required: true,
},
},
参数的默认值
这里仅为示例, 代码不采用, 后续style采用默认值.
1
2
3
4
5
6
7props: {
url: {
type: String,
required: false,
default: 'example.jpg'
},
},
组件样式
增加属性的通用性
特例:
style
属性在使用v-bind
绑定数据时需要绑定一个对象传递样式参数
1
2
3<template>
<img :src="url" :style="{width: size+'px', height: size+'px'}"/>
</template>组件样式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29<template>
<img
class="avatar-img"
:src="url"
:style="{ width: size + 'px', height: size + 'px' }"
/>
</template>
<script>
export default {
props: {
url: {
type: String,
required: true,
},
size: {
type: Number,
},
},
};
</script>
<style>
.avatar-img {
border-radius: 50%;
object-fit: cover;
display: block;
}
</style>
避免冲突样式 (隔绝组件)
使用
scoped
创建带有作用域的样式1
2
3<style scoped>
...
</style>vue-cli
会在类样式选择器及选择选择器加上属性选择器1
2
3.avatar-img[添加的自定义属性] {
...
}