vue中props通信实现双向数据流

vue中组件通过props进行组件通信的时候,props是单向数据流的,也就是只能通过父组件改变值传入到子组件,不能通过子组件改变父组件中的值,但我们实际开发中,有一些场景是需要实现双向数据流的props的,比如我们自定义一个dialog弹窗组件,在弹窗内部的叉号点击关闭弹窗:

1.使用object类型的props传值

//弹窗组件dialog
<template>
  <div class="dialog" :class="{openDialog:visible.showDialog}" @click="close(closeByCover)">
    <!-- 阻止点击事件冒泡 .stop -->
    <div class="dialogContent" @click.stop>
      <i class="close iconfont icon-guanbi" @click="close()"></i>
      <p class="title">{{title}}</p>
      <!-- 弹窗主内容插槽 -->
      <div class="main">
        <slot></slot>
      </div>

      <!-- 弹窗footer插槽,具名插槽 -->
      <div class="footer">
        <slot name="dialog-footer"></slot>
      </div>
    </div>
  </div>
</template>
<script>
/* eslint-disable */
import '@/assets/icons/iconfont.css'
export default {
  props: {
    title: {
      type: String,
      default: 'dialog'
    },
    visible: {
      type: Object,
      default: {showDialog: false},
      required: true
    },
    closeByCover: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    close () {
      this.visible.showDialog = !this.visible.showDialog
    }
  }
}
</script>

父组件中引用:

<Dialog title="工单生成" :visible="showDialog"></Dialog>
export default {
  components: {
    Dialog
  },
  data () {
    return {
    	showDialog: {showDialog: false}
    }
  },
  methods: {
	open() {this.showDialog.showDialog = !this.showDialog.showDialog}
  }
}

2.通过.sync修饰符来实现 (推荐)

//子组件dialog
<template>
  <div class="operationDialog" :class="{openDialog:visible}" @click="close(closeByCover)">
    <!-- 阻止点击事件冒泡 .stop -->
    <div class="dialogContent" @click.stop>
      <i class="close iconfont icon-guanbi" @click="close()"></i>
      <p class="title">{{title}}</p>
      <!-- 弹窗主内容插槽 -->
      <div class="main">
        <slot></slot>
      </div>

      <!-- 弹窗footer插槽,具名插槽 -->
      <div class="footer">
        <slot name="dialog-footer"></slot>
      </div>
    </div>
  </div>
</template>
<script>
/* eslint-disable */
import '@/assets/icons/iconfont.css'
export default {
  props: {
    title: {
      type: String,
      default: 'dialog'
    },
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    closeByCover: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    close (closeByCover = true) {
      // 可手动设置“点击蒙层关闭弹窗”
      if (!closeByCover) return false
      this.$emit('update:visible', false)
    }
  }
}
</script>

在父组件引用:

//通过sync修饰符绑定的props,可以直接在子组件中通过this.$emit('update:propsName',newVal)的方式直接修改父组件中的值
<Dialog title="工单生成" :visible.sync="showDialog"></Dialog>
export default {
  components: {
    Dialog
  },
  data () {
    return {
    	showDialog: false
    }
  },
  methods: {
	open() {this.showDialog= !this.showDialog}
  }
}

你可能感兴趣的:(vue)