VUE3.0 在父子组件中相互触发组件的函数方法

x33g5p2x  于2021-09-30 转载在 Vue.js  
字(0.8k)|赞(0)|评价(0)|浏览(532)

1. 父组件触发子组件的方法

这个是父组件的代码:

<template>
  <Layouts ref="RefChilde">  //第一步写ref
    <router-view>
    </router-view>
  </Layouts>
</template>
<script>
import Layouts from "./layouts/Layouts.vue";  //引入子组件

export default {
  components: {
    Layouts,  //注册
  },
 setup() {
    const RefChilde = ref(); //定义与ref同名变量
    onMounted(() => {
      RefChilde.value.sonFn(); //调用子组件的方法或者变量,通过value
    });
    return{
      RefChilde  //抛出变量
    }
  },
}
</script>

子组件: 

setup() {
const sonFn = () => {
      console.log('调用了');
    };
}

2. 子组件触发父组件的方法 

子组件:

setup(props, context) {
        onMounted(() => {
            context.emit('postData');
        })
}

父组件:

<template>
    <div>
<!-- 1. 监听子组件发射的方法名,调用方法名 -->
        <child @postData="postData"></child>
    </div>
</template>
<script>
 setup() {
        // 2. 定义方法
        const postData = () => {
            console.log('触发父组件的方法');
        }
        return {
            // 3. 抛出去
            postData
        };
    },
    components: {
        child,
    },
}
</script>

相关文章

微信公众号

最新文章

更多