亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue3父組件調(diào)用子組件的方法例子

 更新時(shí)間:2023年07月04日 11:57:43   作者:明明白白的明  
這篇文章主要給大家介紹了關(guān)于vue3父組件調(diào)用子組件的方法例子,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

前言

vue3父組件調(diào)用子組件的方法是通過exposeref來實(shí)現(xiàn)的,我們可以通過expose來控制父組件可以訪問子組件那些的方法和對象,我們將通過setup api(組合式 api)和option api(選項(xiàng)式 api)來演示父組件如何調(diào)用子組件的方法。

1,組合式API

父組件通過ref定義子組件實(shí)例,通過調(diào)用實(shí)例獲得子組件的數(shù)據(jù)和方法

<!-- 父組件 app.vue -->
<template>
  <div class="itxst">
    <!-- 使用 ref  指令關(guān)聯(lián)子組件 -->
    <child ref="childComp"/>
    <button @click="onTry">點(diǎn)擊試一試</button>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import child from "./child.vue";
//定義子組件實(shí)例,名稱要和上面的ref相同
const childComp = ref(null);
//訪問demo組件的方法或?qū)ο?
const onTry = () => {
  //獲取到子組件的 title 數(shù)據(jù) 
  let msg = childComp.value.state.title;
  //調(diào)用子組件的 play方法
  childComp.value.play();
};
</script>

子組件通過defineExpose暴露對象和方法 

<!--子組件名稱  child.vue -->
<template>
  <div class="itxst">
    {{ state.title }}
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
//定義一個(gè)變量
const state = reactive({
  title: "www.itxst.com",
});
//定義一個(gè)方法
const play = () => {
  state.title = "你調(diào)用了子組件的方法";
};
//暴露state和play方法
defineExpose({
  state,
  play,
});
</script>

2,選項(xiàng)式API

<!-- 父組件 app.vue -->
<template>
  <div class="itxst">
    <!-- 使用 ref  命令 -->
    <child ref="childComp"/>
    <button @click="onClick">點(diǎn)擊試一試</button>
  </div>
</template>
<script >
import child from "./child.vue";
export default {
  name: "app",
  //注冊組件
  components: {
    child,
  },
  methods: {
    onClick: function () {
      //獲取到 子組件的  數(shù)據(jù)
      let msg = this.$refs.childComp.message;
      //執(zhí)行了子組件的 play方法
      this.$refs.childComp.play();
    },
  },
};
</script> 
<!-- 子組件 child.vue -->
<template>
  <div class="itxst">
    {{ title }}
  </div>
</template>
<script>
//選項(xiàng)式默認(rèn)當(dāng)前實(shí)例是全部暴露
export default {
  name: "demo",
  //默認(rèn)全部暴露 也可以通過expose控制那些需要暴露
  //expose: ['play'],
  data() {
    return {
      title: "www.itxst.com",
    };
  },
  methods: {
    play: function () {
      this.title = "你調(diào)用了子組件的方法";
    },
  },
};
</script>

總結(jié)

到此這篇關(guān)于vue3父組件調(diào)用子組件的文章就介紹到這了,更多相關(guān)vue3父組件調(diào)用子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論