vue子组件给父组件传值

vue中示例

  1. 子组件:
<template>
    <div class="app">
       <input @click="sendMsg" type="button" value="给父组件传递值">
    </div>
</template>
<script>
export default {
 
    data () {
        return {
            //将msg传递给父组件
            msg: "我是子组件的msg",
        }
    },
     methods:{
         sendMsg(){
             //func: 是父组件指定的传数据绑定的函数,this.msg:子组件给父组件传递的数据
             this.$emit('func',this.msg)
         }
     }
}
</script>

子组件通过this.$emit()的方式将值传递给父组件

注意:这里的func是父组件中绑定的函数名

  1. 父组件:
<template>
    <div class="app">
        <child @func="getMsgFormSon"></child>
    </div>
</template>
<script>
import child from './child.vue'
export default {
    data () {
        return {
            msgFormSon: "this is msg"
        }
    },
    components:{
        child,
    },
    methods:{
            getMsgFormSon(data){
                this.msgFormSon = data
                console.log(this.msgFormSon)
            }
    }
}
</script>

好了,so easy!

uniapp中的示例

  1. 子组件:

components/interactive-bar/interactive-bar.vue

<template>
	<view class="interactiveBar">
		<view class="info">
			<view class="left">
				<view class="item" v-if="type==0">
					<uni-icons type="redo" size="28" color="#999"></uni-icons>
					<text></text>
				</view>
				<view class="item" v-if="type==1" @click="clickCommentBtn">
					<view class="input">评价一下...</view>
				</view>
			</view>
			<view class="right">
				  这里是伪代码 …………
			</view>
		</view>
	</view>
</template>

<script setup>

// 声明组件可以触发的自定义事件,事件名称可以在数组中定义
// 注意:事件名称comment必需与父组件里的@comment一致
const emit = defineEmits(['comment']) 

// 传递一个对象
const commentData = {
	type: 'comment1',
	value: 2,
	timestamp: Date.now()
};
//点击评论框按钮触发
const clickCommentBtn = ()=>{
	console.log("交互子组件");
	// 本页面为子组件,emit是向父组件里提交comment值
	emit("comment",commentData)
}
</script>

<style lang="scss" scoped>

</style>
  1. 父页面

pages/detail/detail.vue

<template>
	<view class="detailLayout">
		<!-- 文章内容 -->
		<view class="soupDetail">
			伪代码
		</view>
		<!-- 评论 -->
		<view class="commnet">
			伪代码
		</view>

		<view class="interactive">
			<!--  @comment="handelComment" 接收子组件传来的comment信息,在handelComment方法中处理逻辑-->
			<interactive-bar  @comment="handelComment"></interactive-bar>
			<!-- 预留出页面底部的安全区域高度 这里使用的是common/style/common-style.scss里的样式-->
			<view class="safe-area-bottom"></view>
		</view>
	</view>

	<!-- 底部弹框评论:safe-area="false" 是否适配底部安全区-->
	<uni-popup type="bottom" ref="commentPopup" :safe-area="false">
		<comment-reply></comment-reply>
	</uni-popup>

</template>

<script setup>
	import {
		ref
	} from 'vue';

	// 评论弹层控制 
	const commentPopup = ref(null);
	// 评论弹层控制 处理逻辑
	const handelComment = (data) => {
		console.log("data:", data)
		console.log("data.type:", data.type)
		commentPopup.value.open();
	}
</script>

<style scoped lang="scss">

</style>
  1. 效果

image

posted @ 2020-05-03 17:48  HaimaBlog  阅读(472)  评论(0)    收藏  举报