uni-app父子组件间的方法调用及传值
方法调用:

一、父组件调用子组件里的方法
1. 先准备一个子组件
<template>
    <view></view>
</template>

<script>
    export default {
        data(){
            return {}
        },
        methods:{
            childMethod() {  // 子组件中有一个childMethod方法
                console.log('childMethod do...')
            }
        }
    }
</script>

2. 准备一个父组件
<template>
    <view class="content">
        <mian-index ref="mainindex"></mian-index> //使用子组件,ref给子组件一个id标识
    </view>
</template>
<script>
    import mainindex from '@/pages/main/index/index.vue'  //引入子组件
    export default {
        data() {
            return {

            };
        },
        components:{
            'mian-index':mainindex
        },
        onLoad(e) {
            this.$refs.mainindex.childMethod();  //页面加载时就调用子组件里的childMethod方法
        }
    }
</script>

参考地址:https://www.cnblogs.com/cap-rq/p/11026881.html

二、子组件调用父组件里的方法
2.1. 准备一个父组件
<template>
   <view class="father">
   	 <child v-on:ToChange="change"></child>  // 在使用子组件时,通过v-on绑定在父组件内定义好的方法
   </view>
</template>

<script>
   import child from '../../components/child'  //引入子组件
   export default { 
   	...
   	methods: {
   		change(){  // 在父组件内定义好的方法
   			console.log("触发了父页面内的方法");
   		},
   	},
   	components:{
   		child
   	}
   }
</script>

2.2. 在准备一个子组件
<template>
   <view @tap="changeC()">  // 在子组件内绑定触发子组件内定义的方法
       子组件
   </view>
</template>

<script>
   export default {
   ...
   	methods:{
   		changeC(type){
   			this.$emit("Tochange");  // 通过this.$emit触发父组件内绑定的方法
   			console.log("触发了子组件内的方法");
   		}
   	}
   }
</script>

参考地址:https://blog.csdn.net/Sport_18/article/details/102833209

传值:

三、父组件给子组件传值
3.1. 父组件:
<template>
	<view>
		<test :msg="msg"></test>  // :msg="msg"绑定传值
	</view>
</template>

<script>
	import test from "@/components/test/test.vue"  // 引入子组件
	export default {
		data () {
			return {
				msg: 'hello'
			}
		},
		components: {test}
	}
</script>

3.2. 子组件:
<template>
	<view>
		子组件 {{msg}}  //接收后使用
	</view>
</template>

<script>
	export default {
		props: ['msg']  //通过props接收数据
	}
</script>

<style>
</style>

四、子组件给父组件传值
4.1. 父组件
<template>
	<view>
		<test @myEvent="getMsg"></test>
	</view>
</template>
<script>
	import test from "@/components/test/test.vue"   // 引入子组件
	export default {
		methods: {
			getMsg (res) {
				console.log(res)
			}
		},
		components: {test}
	}
</script>

4.2.子组件
<template>
	<view>
		<button type="primary" @click="sendMsg">给父组件传值</button>
	</view>
</template>

<script>
	export default {
		data () {
			return {
				status: 'hello uni-app'
			}
		},
		methods: {
			sendMsg () {
				this.$emit('myEvent',this.status)  // 通过$emit触发事件,第二个参数就是传递的参数
			}
		}
	}
</script>

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐