一、父传子
1.1业务逻辑
父组件中点击编辑,将此行的row以对象的方式传到子组件,子组件相应地方显示父组件传过来的内容
1.2功能展示
1.3实现步骤
1.3.1在父组件中引入子组件
// 父组件中引入子组件
import accidentNewDialog from './accidentNewDialog.vue'
1.3.2在父组件中注册并使用子组件
// 父组件中注册子组件
components: {
accidentNewDialog
},
// 父组件中使用子组件
<accident-new-dialog
:depart="curEditOrg"
:dialog-status="dialogStatus"
:show.sync="dialogNewVisible"
@added="onUpdated"
@edited="onUpdated"
/>
1.3.3将父组件的行数据(row)传给子组件
// 父组件中的信息
data() {
return {
curEditOrg: {},
dialogStatus: 'create',
dialogNewVisible: false,
}
},
1.3.4父组件中点击编辑按钮的事件
// 点击编辑按钮事件
<el-table-column
label="操作"
align="center"
width="100"
class-name="small-padding "
>
<template slot-scope="{ row, $index }">
<el-link
class="el-icon-edit-outline btn-oper"
style="font-size: 18px; color: #f4a63f"
@click="handleUpdate(row, $index)" //点击编辑按钮将row传给子组件
/>
<el-link
class="el-icon-close btn-oper"
style="font-size: 18px; color: #e14949"
@click="handleDel(row, $index)"
/>
</template>
</el-table-column>
methods:{
handleUpdate(row) {
this.curEditOrg = row
this.dialogStatus = 'update'
this.dialogNewVisible = true
},
}
1.3.5子组件接收并显示数据
子组件通过props进行获取
// props获取
props: {
show: {
type: Boolean,
default: false
},
dialogStatus: {
type: String,
default: ''
},
depart: {
type: Object,
default: () => {}
}
},
1.3.6子组件监听一下获取过来的数据
watch: {
show(val) {
this.dialogVisible = val
},
depart(val) {
this.temp = JSON.parse(JSON.stringify(val))
}
},
1.3.7打印一下获取火来的数据,就可以操作了
// 在created生命周期里打印一下
created(){
console.log(this.depart)
}
二、子传父
2.1.业务逻辑
子组件中点击选择文件类型,将类型传到父组件中,并根据类型显示不同数据
2.2功能展示
2.3实现步骤
2.3.1子组件点击事件
// 点击安全管理文件
<el-tree
:data="treeNodes"
node-key="id"
icon-class="el-icon-suitcase"
default-expand-all
current-node-key="1"
:highlight-current="true"
:props="treeProps"
@node-click="handleNodeClick" //点击事件
/>
2.3.2子组件通过this.$emit注册方法
methods:{
handleNodeClick(node) {
this.$emit('handleNodeClick', node) //父组件只需要调用这个方法就可以了
},
}
2.3.3父组件中引入子组件
// 父组件中引入子组件
import fileTypeTree from '@/components/common/fileTypeTree.vue'
// 父组件中注册子组件
components:{
fileTypeTree,
}
// 父组件中使用子组件,并利用子组件注册的方法,更新表格数据
<fileType-tree @handleNodeClick="onSelNodeChange" /> //handleNodeClick为子组件注册的方法
// 父组件使用onSelNodeChange方法,调取接口更新数据
data(){
return{
listQuery: {
page: 1,
limit: 20,
keyWord: '',
fileType: 0
},
}
},
methods:{
onSelNodeChange(node) {
this.listQuery.fileType = node.key
this.getList() //更新表格数据方法
},
getList() { //更新表格数据方法
this.listLoading = true
this.listQuery.keyWord = this.listQuery.keyWord.trim()
getRuleList(this.listQuery)
.then(res => {
console.log(res)
res.data.rows.forEach(item => {
if (item.zdDate) {
item.zdDate = Time(item.zdDate)
}
switch (item.fileGs) {
case '0':
item.fileGs = 'docs'
break
case '1':
item.fileGs = 'xls'
break
case '2':
item.fileGs = 'zip'
break
}
})
this.listLoading = false
this.list = res.data?.rows || []
this.total = res.data?.total || 0
})
.catch(err => {
this.list = []
this.total = 0
console.log(err)
})
},
}