方法一:
1 <!--父组件代码--> 2 <template> 3 <div> 4 <p>我是父组件</p> 5 <button @click="handleShowChild" v-show="!isVisibleChild">显示子组件</button> 6 <child :visible = 'isVisibleChild' @handleHideChild="handleHideChild"></child> 7 </div> 8 </template> 9 <script> 10 import child from './child' 11 export default { 12 data(){ 13 return { 14 isVisibleChild: false 15 } 16 }, 17 components:{ 18 child 19 }, 20 methods:{ 21 handleShowChild(){ 22 this.isVisibleChild = true; 23 }, 24 handleHideChild(flag){ 25 this.isVisibleChild = flag; 26 } 27 } 28 } 29 </script> 30 31 <!--子组件代码--> 32 <template> 33 <div v-show="visible"> 34 <p>我是子组件</p> 35 <button>隐藏子组件</button> 36 </div> 37 </template> 38 39 <script> 40 export default { 41 name:'child', 42 props:{ 43 visible: { 44 type: Boolean, 45 default: false 46 } 47 }, 48 methods:{ 49 handleHideChild(){ 50 this.$emit('handleHideChild',false) 51 } 52 } 53 54 } 55 </script>
方法二:sync+update方法
1 <!--父组件代码--> 2 <template> 3 <div> 4 <p>我是父组件</p> 5 <button @click="handleShowChild" v-show="!isVisibleChild">显示子组件</button> 6 <child :visible.sync = 'isVisibleChild'></child> 7 </div> 8 </template> 9 <script> 10 import child from './child' 11 export default { 12 data(){ 13 return { 14 isVisibleChild: false 15 } 16 }, 17 components:{ 18 child 19 }, 20 methods:{ 21 handleShowChild(){ 22 this.isVisibleChild = true; 23 }, 24 } 25 } 26 </script> 27 28 <!--子组件代码--> 29 <template> 30 <div v-show="visible"> 31 <p>我是子组件</p> 32 <button>隐藏子组件</button> 33 </div> 34 </template> 35 36 <script> 37 export default { 38 name:'child', 39 props:{ 40 visible: { 41 type: Boolean, 42 default: false 43 } 44 }, 45 methods:{ 46 handleHideChild(){ 47 this.$emit('update:visible',this.visible=false) 48 } 49 } 50 51 } 52 </script>
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/281591.html