子组件向父组件传值,自定义事件
2021-02-25 本文已影响0人
媛猿YY
需求:
描述:在主页点击购物车弹出提示弹窗
父组件:index.vue
子组件:modal.vue
代码:
modal.vue
<template>
<div class="modal" v-show="showModal">
<div class="mask"></div>
<div class="modal-dialog">
<div class="modal-header">
<span>{{ title }}</span>
<a href="javascript:;" class="icon-close" @click="$emit('cancel')"></a>
</div>
<div class="modal-body">
<slot name="body"></slot> // 插槽的用法
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn" v-if="btnType == 1" @click="$emit('submit')">{{ sureText }}</a> //emit 将自定义函数submit传值给父组件
<a href="javascript:;" class="btn" v-if="btnType == 2" @click="$emit('cancel')">{{ cancelText }}</a> //emit 将自定义函数cancel传值给父组件
<div class="btn-group" v-if="btnType == 3">
<a href="javascript:;" class="btn" @click="$emit('submit')">{{ sureText }}</a>
<a href="javascript:;" class="btn" @click="$emit('cancel')">{{ cancelText }}</a>
</div>
</div>
</div>
</div>
</template>
<script>
// @ is an alias to /src
export default {
name: 'modal',
props: {//接收从父组件传过来的值
// 弹框类型:小 small /中 midlle/ 大 large / 表单form
modalType: {
type: String,
default: 'form',
},
// 弹框标题
title: String,
// 按钮类型:1 、确定 ,2、取消,3、确定、取消
btnType: String,
sureText: {
type: String,
default: '确定',
},
cancelText: {
type: String,
default: '取消',
},
showModal: Boolean,
},
data() {
return {
};
},
components: {},
};
</script>
index.vue
<template>
<modal
title="提示"
sureText="查看购物车"
btnType="1"
modalType="middle"
:showModal="showModal"
@submit="goToCart" //子组件的自定义函数submit
@cancel="showModal=false" //子组件的自定义函数cancel
>
<template v-slot:body>
<p>商品添加成功!</p>
</template>
</modal>
</template>
<script>
import Modal from './../components/Modal';
export default {
data(){
return{
showModal: false,
}
}
}
</script>