指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

vue3父组件通过组合式API调用子组件的方法:

<!-- 父组件 app.vue -->
<template>
  <div class="itxst">
    <!-- 使用 ref  指令关联子组件 -->
    <child ref="childComp"/>
    <button @click="onTry">点击试一试</button>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import child from "./child.vue";
//定义子组件实例,名称要和上面的ref相同,这个很重要
const childComp = ref(null);

//访问demo组件的方法或对象
const onTry = () => {
  //获取到子组件的 title 数据 
  let msg = childComp.value.state.title;
  //调用子组件的 play方法
  childComp.value.play();
};
</script>

<!--子组件名称  child.vue -->
<template>
  <div class="itxst">
    {{ state.title }}
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
//定义一个变量
const state = reactive({
  title: "www.itxst.com",
});
//定义一个方法
const play = () => {
  state.title = "你调用了子组件的方法";
};

//暴露state和play方法,下面这种方法用的不多,一般都是defineProps()
defineExpose({
  state,
  play,
});
</script>

传统的(vue2)语法:

<!-- 父组件 app.vue -->
<template>
  <div class="itxst">
    <!-- 使用 ref  命令 -->
    <child ref="childComp"/>
    <button @click="onClick">点击试一试</button>
  </div>
</template>
<script >
import child from "./child.vue";
export default {
  name: "app",
  //注册组件
  components: {
    child,
  },
  methods: {
    onClick: function () {
      //获取到 子组件的  数据
      let msg = this.$refs.childComp.message;
      //执行了子组件的 play方法
      this.$refs.childComp.play();
    },
  },
};
</script> 

<!-- 子组件 child.vue -->
<template>
  <div class="itxst">
    {{ title }}
  </div>
</template>
<script>
//选项式默认当前实例是全部暴露
export default {
  name: "demo",
  //默认全部暴露 也可以通过expose控制那些需要暴露
  //expose: ['play'],
  data() {
    return {
      title: "www.itxst.com",
    };
  },
  methods: {
    play: function () {
      this.title = "你调用了子组件的方法";
    },
  },
};
</script>