组件(Component)是 Vue.js 最强大的功能之一,之前的文章都只是用到了基本的封装功能,这次将介绍一些更强大的扩展。
一、基本用法
在使用 vue-cli 创建的项目中,组件的创建非常方便,只需要新建一个 .vue 文件,然后在 <template> 中写好 HTML 代码,一个简单的组件就完成了这里面使用了vant 有赞的组建,详情可以查看https://youzan.github.io/vant/#/zh-CN/intro
/*
* @Author: guofeng
* @Date: 2018-09-22 15:30:00
* @Last Modified by: guofeng
* @Last Modified time: 2018-09-22 15:46:53
*/
<template>
<div>
<van-swipe :autoplay="3000" @change="onChange">
<van-swipe-item v-for="(image, index) in images" :key="index">
<img v-lazy="image" />
</van-swipe-item>
</van-swipe>
</div>
</template>
<script>
import { Swipe, SwipeItem } from 'vant'
export default {
name: 'AddressForm',
components: {
'van-swipe': Swipe,
'van-swipe-item': SwipeItem
},
props: {
images: {
type: Array,
default: function () {
return [ 'https://img.yzcdn.cn/1.jpg',
'https://img.yzcdn.cn/2.jpg']
}
}
},
data () {
return {
}
},
mounted () {
},
computed: {
},
methods: {
onChange (index) {
// Toast('当前 Swipe 索引:' + index)
}
}
}
</script>
<style>
</style>
一个完整的组件,除了 <template> 以外,还有 <script> 和 <style>
需要注意的是,<script> 中的 data 必须是函数
然后在其他文件的.vue 里面引入并注册,就能直接使用这个组件了
二、使用 slot 分发内容
开发过程中,常常需要在子组件内添加新的内容,这时候可以在子组件内部留一个或者多个插口 <slot>
<!-- 固定header布局 -->
<template>
<section class="fixed-head">
<header
v-if="headHeight!=0"
:style="{
height: headHeight
}">
<slot name="header"></slot>
</header>
<section
class="header-seat"
:style="{
height: headHeight
}"></section>
<section
class="fixed-head__view-port"
:style="{
bodyStyle
}">
<slot></slot>
</section>
</section>
</template>
<script>
export default {
name: 'FixedHead',
props: {
headHeight: {
type: [String, Number],
default: '3.0625rem' // 49px
},
bodyStyle: {
type: Object,
default () {
return {}
}
}
}
}
</script>
<style lang="less" scoped>
@import url('../style/mixins.less');
.fixed-head {
header {
position: fixed;
top: 0;
left: 0;
width: 100%;
overflow: hidden;
z-index: 990;
}
.header-seat {
background: #fff;
}
&__view-port {
width: 100%;
}
.fixed-head__view-port{
position: relative;
z-index: 10;
}
}
</style>
然后在调用这个子组件的时候加入内容
添加的内容就会分发到对应的 <slot> 中
<slot> 中还可以作为一个作用域,在子组件中定义变量,然后在父组件中自定义渲染的方式
这个示例中,首先在子组件中添加 <slot>,并在子组件中定义了数组变量 navs
然后在父组件中以作用域 <template> 添加内容,其中 scope 是固有属性,它的值对应一个临时变量 props
而 props 将接收从父组件传递给子组件的参数 navs
效果展示: