vue自定义指令+组件结合操作实践
指令 + 组件 实现预览功能 可能不符合实际代码规范
const detail = {
inserted (el, binding, vnode) {
// el 绑定对应元素的dom
// binding 传递参数,使用binding.value获取
// vnode 获取当前组件内 this
el.addEventListener('click', (e) => {
// 获取this
const _this = vnode.context
// 解构获取数据
const { formName, rowData } = binding.value
// 将单条数据绑定到对应组件form中
_this[formName] = rowData
// 自定义组件定义ref属性,使用该属性操作子组件中的data数据,显示dialog
_this.$refs.DialogView.dialogVisible = true
// 将对应的表格row对象传递给子组件
_this.$refs.DialogView.rowData = rowData
})
}
}
// 配合全局组件DialogView使用,父组件自定义传递source + 指令传递对应row对象 结合显示
<template>
<div>
<el-dialog
:title="title"
:visible.sync="dialogVisible"
:width="width"
top="35px"
:close-on-click-modal="false"
:close-on-press-escape="false"
>
<el-descriptions :column="2" border>
<el-descriptions-item
v-for="item in source"
:key="item.label"
:label="item.label"
>
{{
rowData[item.props] && rowData[item.props].name
? rowData[item.props].name
: rowData[item.props]
}}
<el-button
v-if="['file1', 'file2'].includes(item.props) && rowData[item.props] && rowData[item.props].name"
type="success"
size="mini"
class="l20"
@click="down(rowData[item.props].url)"
>原文件下载</el-button
>
</el-descriptions-item>
</el-descriptions>
<slot name="footer">
<span slot="footer">
<el-button @click="confirm">关闭</el-button>
</span>
</slot>
</el-dialog>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: '查看'
},
width: {
type: String,
default: '35%'
},
source: {
type: Array,
require: true
}
},
data () {
return {
dialogVisible: false,
rowData: {}
}
},
methods: {
confirm () {
this.dialogVisible = false
},
down (url) {
console.log(url)
}
}
}
</script>
<style lang="scss" scoped>
.l20 {
margin-left: 20px;
}
</style>
// 原始操作 添加点击事件函数
// 指令操作 添加自定义指令 传递对应参数
<el-table-column label="操作" align="center">
<template slot-scope="scope">
<el-tag
size="small"
v-detail="{ 'rowData': scope.row, 'formName': 'form' }"
>详细</el-tag
>
<!-- <el-tag size="small" @click="handleClick(scope)">详细</el-tag> -->
</template>
</el-table-column>
<DialogView
ref="DialogView"
width="50%"
:source="[
{
props: 'zName',
label: '中文名称'
},
{
props: 'eName',
label: '英文名称'
}
]"
>
</DialogView>


愿以往所学皆有所获

浙公网安备 33010602011771号