文章目录
- 一、父组件调用子组件里的方法
- 1. 先准备一个子组件
- 2. 准备一个父组件
- 二、子组件调用父组件里的方法
- 2.1. 准备一个父组件
- 2.2. 在准备一个子组件
- 三、父组件给子组件传值
- 3.1. 父组件:
- 3.2. 子组件:
- 四、子组件给父组件传值
- 4.1. 父组件
- 4.2.子组件
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>