父组件调用子组件方法

通过ref来确定那个组件

<!-- test-god父组件 -->
<template>
  <div>
    <a @click="showSon()">显示子组件</a>
    <a @click="hideSon()">隐藏子组件</a>
    <show-box ref="box"></show-box>
  </div>
</template>
<script>
import ShowBox from 'views/test/show-box'
export default {
  methods: {
    showSon() {
      this.$refs.box.show()
    },
    hideSon() {
      this.$refs.box.hide()
    }
  },
  components: {
    ShowBox
  }
}
</script>
<!-- show-box子组件 -->
<template>
  <div class="show-box" v-if="flag">
    <div class="box">
      子组件
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      flag: false
    }
  },
  methods: {
    show() {
      this.flag = true
    },
    hide() {
      this.flag = false
    }
  }
}
</script>
<style lang="scss" scoped>
.show-box{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate3d(-50%, -50%, 0);
  transform: -webkit-translate3d(-50%, -50%, 0);
  transform: -ms-translate3d(-50%, -50%, 0);
  transform: -moz-translate3d(-50%, -50%, 0);
  .box{
    background-color: red;
    width: 300px;
    height: 300px;
  }
}

</style>

posted @ 2018-03-23 18:37  海螺呜呜  阅读(270)  评论(0编辑  收藏  举报