- 在vue中父组件向自子组件传递props;
- 子组件向父组件传递属性是用$emit(发布订阅);
实例基本逻辑:
点击页面上一个按钮,弹出弹框,点击弹框上关闭按钮,隐藏弹框
<style>
.mark{ width: 100%; height: 100%; position: fixed; top: 0; left: 0; background: rgba(0,0,0,.4); }
.modal{ width: 300px; height: 200px; background: #ffffff; padding: 10px; position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); }
</style>
需要对“打开弹窗”按钮定义一个变量命名为
state
,当state=true
时弹出;
弹框弹出后,在子组件内,需要$emit
一个关闭事件把state
变成false
从而关闭弹框
<body>
<div id="app">
<button @click="state=true">打开弹窗</button>
<mymodal :show="state" @close="()=>state=false"></mymodal>
</div>
<template id="temp1">
<div class="mark" v-if="show">
<div class="modal">
<button @click="modalClose">关闭弹窗</button>
</div>
</div>
</template>
</body>
<script type="text/javascript">
let mymodal = {
props:['show'],
template:'#temp1',
methods:{
modalClose(){
this.$emit('close')
}
}
};
let app = new Vue({
el: "#app",
data: {
state:false
},
components: {
mymodal
}
});
</script>
网友评论