vue+iview 实现父组件在子组件表格中添加日期选择器
时间: 2023-08-18 21:13:10 浏览: 167
基于Vue组件化的日期联动选择器功能的实现代码
可以通过在子组件的表格列定义中使用`scoped-slot`来自定义渲染日期选择器,然后在父组件中传递一个日期选择器的`props`给子组件,在子组件中使用该`props`来控制日期选择器的显示和隐藏。
以下是一个简单的示例代码:
在父组件中:
```
<template>
<div>
<DatePicker v-model="selectedDate" />
<Table :data="tableData">
<Table-column prop="name" label="姓名" />
<Table-column prop="age" label="年龄" />
<Table-column label="生日">
<template slot-scope="{row}">
<Date-Picker
v-show="row.showDatePicker"
v-model="row.birthday"
type="date"
@on-ok="hideDatePicker(row)"
/>
<div v-else @click="showDatePicker(row)">{{ row.birthday }}</div>
</template>
</Table-column>
</Table>
</div>
</template>
<script>
import { DatePicker, Table } from "iview";
export default {
components: {
DatePicker,
Table
},
data() {
return {
selectedDate: null,
tableData: [
{
name: "张三",
age: 20,
birthday: "1999-01-01",
showDatePicker: false
},
{
name: "李四",
age: 22,
birthday: "1997-06-15",
showDatePicker: false
},
{
name: "王五",
age: 25,
birthday: "1994-11-30",
showDatePicker: false
}
]
};
},
methods: {
showDatePicker(row) {
row.showDatePicker = true;
},
hideDatePicker(row) {
row.showDatePicker = false;
}
}
};
</script>
```
在子组件中:
```
<template>
<div>
<Table :data="tableData">
<Table-column prop="name" label="姓名" />
<Table-column label="生日">
<template slot-scope="{row}">
<Date-Picker v-model="row.birthday" type="date" />
</template>
</Table-column>
</Table>
</div>
</template>
<script>
import { DatePicker, Table } from "iview";
export default {
components: {
DatePicker,
Table
},
props: {
datePickerProps: Object
},
data() {
return {
tableData: [
{
name: "张三",
birthday: "1999-01-01"
},
{
name: "李四",
birthday: "1997-06-15"
},
{
name: "王五",
birthday: "1994-11-30"
}
]
};
}
};
</script>
```
在父组件中使用子组件时,传递日期选择器的`props`:
```
<template>
<div>
<DatePicker v-model="selectedDate" />
<ChildComponent :datePickerProps="datePickerProps" />
</div>
</template>
<script>
import ChildComponent from "./components/ChildComponent.vue";
export default {
components: {
ChildComponent
},
data() {
return {
selectedDate: null,
datePickerProps: {
type: "date"
}
};
}
};
</script>
```
这样就可以在子组件的表格列中渲染日期选择器,并且可以根据`props`来控制日期选择器的显示和隐藏了。
阅读全文