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

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

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

前言

vue3父組件調(diào)用子組件的方法是通過exposeref來實(shí)現(xiàn)的,我們可以通過expose來控制父組件可以訪問子組件那些的方法和對(duì)象,我們將通過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暴露對(duì)象和方法 

<!--子組件名稱  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)全部暴露 也可以通過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)論

孟州市| 甘泉县| 河北省| 梓潼县| 阳原县| 鹤岗市| 苍梧县| 余庆县| 镇原县| 平谷区| 会泽县| 河西区| 澄江县| 大新县| 固阳县| 化德县| 平果县| 唐河县| 萍乡市| 溧阳市| 巴彦县| 晋城| 铁岭县| 阿拉善左旗| 文登市| 利津县| 宣恩县| 高淳县| 山东| 福州市| 佳木斯市| 玛纳斯县| 盐津县| 沂水县| 姚安县| 恭城| 鲁甸县| 奎屯市| 柘城县| 云龙县| 离岛区|