最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

详解vue父子组件关于模态框状态的绑定方案

来源:动视网 责编:小采 时间:2020-11-27 21:55:37
文档

详解vue父子组件关于模态框状态的绑定方案

详解vue父子组件关于模态框状态的绑定方案:日常开发中经常遇到的一个场景,父组件有很多操作,需要弹窗,例如: <template> <div class=page-xxx> //点击打开新增弹窗 <button>新增</button> //点击打开编辑弹窗 <button>编辑</butt
推荐度:
导读详解vue父子组件关于模态框状态的绑定方案:日常开发中经常遇到的一个场景,父组件有很多操作,需要弹窗,例如: <template> <div class=page-xxx> //点击打开新增弹窗 <button>新增</button> //点击打开编辑弹窗 <button>编辑</butt


日常开发中经常遇到的一个场景,父组件有很多操作,需要弹窗,例如:

<template>
 <div class="page-xxx">
 //点击打开新增弹窗
 <button>新增</button>
 //点击打开编辑弹窗
 <button>编辑</button>
 //点击打开详情弹窗
 <button>详情</button>
 <Add :showAdd="false"></Add>
 <Edit :showEdit="false"></Edit>
 <Detail :showDetail="false"></Detail>
 </div>
</template>

子组件:

<div class="page-add">
 <el-dialog :visible="dialogVisible" @close="handleClose"></el-dialog>
</div>
<script>
export default {
 data() {
 return {
 dialogVisible: false,
 }
 },
 methods: {
 handleClose(val) {
 this.dialogVisible= false
 },
 },
}
</script>

如何实现子组件和父组件模态框状态的同步

方案一:使用.sync 修饰符

父组件:

<template>
 <div class="page-xxx">
 //点击打开新增弹窗
 <button @click="show = true">新增</button>
 <Add :show.sync="show"></Add>
 </div>
</template>

子组件:

<div class="page-add">
 <el-dialog:visible="dialogVisible" @close="handleClose"></el-dialog>
</div>
<script>
export default {
 props: {
 show: {
 type: Boolean
 }
 },
 watch: {
 show(value) {
 this.dialogVisible= value
 }
 },
 data() {
 return {
 dialogVisible: false,
 }
 },
 methods: {
 handleClose(val) {
 this.$emit('update:show', false);
 },
 },
}
</script>

方案二:使用v-model

父组件:

<template>
 <div class="page-xxx">
 //点击打开新增弹窗
 <button @click="show = true">新增</button>
 <Add v-model="show"></Add>
 </div>
</template>

子组件:

<div class="page-add">
 <el-dialog :visible="dialogVisible" @close="handleClose"></el-dialog>
</div>
<script>
export default {
 props: {
 show: {
 type: Boolean
 }
 },
 watch: {
 show(value) {
 this.dialogVisible= value
 }
 },
 data() {
 return {
 dialogVisible: false,
 }
 },
 methods: {
 handleClose(val) {
 this.$emit('input', false)
 },
 },
}
</script>

computed OR watch ?

对于上面的两种方案,子组件内部还可以使用计算属性的写法

computed
export default {
 props: {
 show: {
 type: Boolean
 }
 },
 computed: {
 dialogVisible: {
 get() {
 return this.show
 },
 set(value) {
 return this.$emit('input', value)
 },
 },
 },
 methods: {
 handleClose(val) {},
 },
}

文档

详解vue父子组件关于模态框状态的绑定方案

详解vue父子组件关于模态框状态的绑定方案:日常开发中经常遇到的一个场景,父组件有很多操作,需要弹窗,例如: <template> <div class=page-xxx> //点击打开新增弹窗 <button>新增</button> //点击打开编辑弹窗 <button>编辑</butt
推荐度:
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top