一 在前端开发过程中,很多情况下一个页面无法装载大部分的代码,所以需要子组件来完成父组件的任务,下面我来展示一下,组件之间如何进行传值以及常见的坑,首先上代码
1.1 父组件代码
<template>
<div class="app-container">
<eHeader :query="query"/>
<el-table v-loading="loading" ref="table" :data="data" size="small" style=" 100%;">
<el-table-column prop="type" label="xxx"/>
<el-table-column prop="public_address" label="xxx"/>
<el-table-column prop="private_address" label="xxx"/>
<el-table-column prop="location" label="xxx"/>
<el-table-column prop="strategy" label="xxx"/>
<el-table-column prop="dns" label="xxx"/>
<el-table-column prop="status" label="xxx"/>
<el-table-column prop="reboot_time" label="xxx"/>
<el-table-column label="xxx" width="240px" align="center">
<template slot-scope="scope">
<el-button v-if="checkPermission(['xxx'])" type="primary" size="mini" plain @click="getuser(scope.row)" style="margin-left:0px">用户详情</el-button>
</template>
</el-table-column>
<!--<el-table-column prop="desc" label="备注"/>-->
</el-table>
<!--抽屉组件-->
<eDrawer @sendVal="closeDialog" :isDrawerShow="isDrawerShow" :drawerData="drawerData"/>####这里将数据布尔值以及函数传给子组件
<!--分页组件-->
<el-pagination
:total="total"
:page-sizes="[25, 50, 100, 200]"
style="margin-top: 8px;"
layout="total, prev, pager, next, sizes"
@size-change="sizeChange"
@current-change="pageChange"/>
</div>
</template>
<script>
import initData from '@/mixins/initData'
import { getKey } from '@/api/dict'
import { parseTime } from '@/utils/index'
import eHeader from './module/header'
import eDrawer from './module/drawer' ##这里引入抽屉子组件export default {
components: { eHeader,eDrawer },
mixins: [initData],
data() {
return {
row_data: null,
span1: 24,
show: false,
table_show: true,
transfer_data: [],
Loading: false,
sup_this: this,
isDrawerShow:false,###需要传入子组件的布尔值,true打开,false关闭
drawerData:{} ###传入子组件的数据
}
1.2 子组件代码
<template>
<div>
<el-drawer
title="用户详情!"
:visible.sync="is_show" ####与局部变量is_show绑定,true打开,false关闭
direction="rtl"
size="50%">
<div class="item">
<p class="labelContent">备注:</p>
<p class="contentN">{{drawerData.public_address}}</p>
</div>
</el-drawer>
</div>
</template>
<script>
export default {
props:{#用prop来接收父组件的值,由于数据不需要回传和改变直接使用
isDrawerShow: {
type: Boolean,
required: true
},
drawerData:{#布尔值会改变,需要引入局部变量is_show中
type: Object,
required: true
},
},
computed: {
is_show: {
set(val){##改变父组件中的值
this.$emit('sendVal',val)
},
get(){##获取父组件的值
return this.isDrawerShow
}
}
}
}
</script>
总结:父组件的值传给子组件之后,不能直接改变,否则会出现一些奇怪的错误,一般定义到子组件的局部变量中,并且当要改变的时候由父组件发起