一、 关于组件
-
组件的应用场景及什么是组件
作为vue开发新手来说,了解并应用组件是vue开发中的必备技能;在前端项目工程中,往往会涉及到大量的功能结构拆分,大量的类似的功能复用,也可能是基于让代码的可读性更高;在这些时候 我们需要使用模块拆分,将拆分的模块做成 组件 指令等;但我在vue的使用中,使用组件比较多;
组件其实就是vue实例的一种属性,在vue实例应用中属性名称标记为components;与组件紧密相连的概念就是模块化,因为模块化的项目开发架构,导致了很多内聚性较高的功能或逻辑形成了一个组件;那么如果想调用这些组件,则需要模块化的导入 导出即可;也就是组件实现了模块化;当然 实现模块化开发并不一定通过组件这种实现方式;也可以通过 指令 页面拆分 等等,但组件一定是模块化的结果;
综上所述,组件是模块化的应用实现方式,模块化是组件的理论指导;即使在vue架构的平台中,实现模块化的方式也不仅仅只有组件
二、 组件的应用案例
- 组件文档
关于组件的基础文档,我将不再做详细讲解;在此可以点击vue组件
- 实现一个父子调用的组件,并相互传递数据
用组件实现一个form模块,并实现在主页(父组件)打开form,在form页不关闭(子组件)
showCmd : 父组件属性,在标签中传入;在子组件中使用props属性获得
formson : 父组件接收 $emit数据提交
子组件
<template>
<div class="cmp-container" :style="{ left: left + 'px', top: top + 'px' }">
<van-row>
<van-col>
<van-cell :title="showCmd" icon="close">
</van-cell>
</van-col>
</van-row>
<van-row>
</van-row>
<van-row>
<van-goods-action>
<van-col span="8">
<van-goods-action-icon icon="description" text="预览" dot @click="onClose" >
</van-goods-action-icon>
</van-col>
<van-col span="8">
<van-goods-action-button
text="提交"
type="info"
@click="onClose"
></van-goods-action-button>
</van-col>
<van-col span="8">
<van-goods-action-button
text="关闭"
type="info"
color="#7232dd"
@click="onClose"
></van-goods-action-button>
</van-col>
<van-col span="3"></van-col>
</van-goods-action>
</van-row>
</div>
</template>
<script>
export default {
name: "index",
props: { //props 从父组件接收传递参数
// 距离上有下左的安全距离
padding: {
type: String,
default: '10 10 10 10'
},
showCmd: {//父组件传递过来的,控制此子组件是否展示
type: String,
default: ''
}
},
data(){
return{
currentTop: 0,
clientWidth: 0,
clientHeight: 0,
itemWidth: 0,
itemHeight: 0,
left: 0,
top: 0
}
},
methods:{
onClose (){
this.$emit('formson', '');//提交关闭,将数据传递给父组件
}
}
}
</script>
<style scoped>
.cmp-container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
position: fixed;
background: rgb(255, 255, 255);
box-shadow: 0px 2px 10px 0px rgba(198, 198, 198, 0.5);
z-index: 9999;
transition: all 0.3s;
}
</style>
父组件
<template>
<div>
<van-button
icon="friends-o"
type="info"
plain
size="small"
class="popup-button-one"
@click="cmdFunc('p2p')"
>P2P
</van-button>
<p2p-form padding="10 10 60 10" @formson="fromsonFn" v-show="showCmd === 'p2p'" :showCmd="showCmd"></p2p-form>
</div>
</template>
<script>
import P2pForm from '@/components/P2pForm';//引入组件
export default {
name: "srvmanage",
data (){
return {
showCmd: '',}},
methods :{
fromsonFn(val){//监听子组件关闭事件
console.log('this srvmange val: ', val, this.showCmd);
this.showCmd=val;
console.log('this srvmange val: ', val, this.showCmd);
},
cmdFunc (type, more='') {//控制是否展示
this.showCmd = type;
}
},
components:{ //组件注册
P2pForm
}
}
</script>