vue项目中,父组件与子组件的传参问题

1.在父组件中

<template>

  <div class="app">

    <Button @click="filterShow=true">控制组件的显隐</Button>

    <child :filterShow="filterShow" @getState="getType"></child>

  </div>

</template>

 

<script>

import child from './components/child'    //子组件所在的位置
 
export default {
  data(){
    return{
      filterShow: false, //开始让子组件隐藏
    }
  },
  components:{
    child,
  },
  methods: {
    //获得从子组件传回的数据
    getType(val){
      this.filterShow = val
    }
  },
}

</script>

 

2.在子组件中

<template>

  <div class="child">

    <Button @click="closeChild">关闭组件</Button>

  </div>

</template>

 

<script>

export default {
  props:{
    filterShow:{
      type: Boolean
    }
  },//组件数据为对象
  data(){
    return{      
      flag: false, //定义新的存放数据
    }
  },
  methods: {
    //关闭子组件 && 子组件向父组件传数据
    closeChild(val){
      this.flag= false;
      this.$emit("getState", this.flag); //向父组件传的this.flag为false
    }
  },
  watch:{//监听从父组件中filterShow传到子组件的val
    filterShow(val){
      this.flag = val;   //开始时this.flag为true
    }
  },
}

</script>

posted @ 2019-03-07 14:09  兜兜biubiu  阅读(595)  评论(0编辑  收藏  举报