最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

前言

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

1,組合式API

父組件通過(guò)ref定義子組件實(shí)例,通過(guò)調(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í)例,名稱(chēng)要和上面的ref相同
const childComp = ref(null);
//訪問(wèn)demo組件的方法或?qū)ο?
const onTry = () => {
  //獲取到子組件的 title 數(shù)據(jù) 
  let msg = childComp.value.state.title;
  //調(diào)用子組件的 play方法
  childComp.value.play();
};
</script>

子組件通過(guò)defineExpose暴露對(duì)象和方法 

<!--子組件名稱(chēng)  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",
  //注冊(cè)組件
  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)全部暴露 也可以通過(guò)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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

洛宁县| 永宁县| 静海县| 定兴县| 阿拉尔市| 桂东县| 顺平县| 青河县| 建阳市| 江津市| 衡水市| 嫩江县| 武宁县| 平阴县| 分宜县| 社会| 江川县| 离岛区| 泸州市| 鸡东县| 洪泽县| 金秀| 长宁县| 西昌市| 六枝特区| 桃江县| 鹿泉市| 沂源县| 崇明县| 含山县| 卓资县| 加查县| 桃江县| 张掖市| 湄潭县| 延津县| 高邑县| 吉安市| 新龙县| 读书| 辉南县|