vue通过props设置子组件的显示与隐藏

vue通过props设置子组件的显示与隐藏

因为vue本身为了保证单向数据流,所以在子组件内部不能直接修改props。

可以通过$emit触发父组件内的事件。

this.$emit(‘update:visible’, false)通知父组件,直接修改visible为false。

父级

<template>
  <div>
    <children :visible="visible"></children>
    <button @click="open"></button>
  </div>
</template>
<script>
import children from './components/children';
export default {
  name: 'parent',
  components: {
    children
  },
  data () {
    return {
      visible: false // 子组件显示与隐藏
    };
  },
  methods: {
    open () {
      this.visible = true;
    }
  }
};
</script>

子组件,注意 .sync

<template>
  <el-dialog width="800px"
             title="子组件"
             :visible.sync="visible"
             :before-close="close">
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="close">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  name: 'children',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {};
  },
  methods: {
    close () {
      this.$emit('update:visible', false);
    }
  }
};
</script>

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注