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

vue3父子組件相互調(diào)用方法詳解

 更新時(shí)間:2024年05月14日 08:50:41   作者:前端開發(fā)菜鳥的自我修養(yǎng)  
在vue3項(xiàng)目開發(fā)中,我們常常會(huì)遇到父子組件相互調(diào)用的場景,下面主要以setup語法糖格式詳細(xì)聊聊父子組件那些事兒,并通過代碼示例介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下

1、前言

在vue3項(xiàng)目開發(fā)中,我們常常會(huì)遇到父子組件相互調(diào)用的場景,下面主要以setup語法糖格式詳細(xì)聊聊父子組件那些事兒

2、子組件調(diào)用父組件方法(setup組合式)

2.1 父組件Father.vue

<template>
	<child @sayHello="handle" />
</template>
 
<script setup>
	import Child from './components/child.vue';
	const handle = () => {
		console.log('子組件調(diào)用了父組件的方法')
	}
</script>

2.2 子組件Child.vue

<template>
	<view>我是子組件</view>
	<button @click="sayHello">調(diào)用父組件的方法</button>
</template>
 
<script setup>
	const emit = defineEmits(["sayHello"])
	const sayHello = () => {
		emit('Hello World')
	}
</script>

3、父組件調(diào)用子組件方法(setup組合式)

3.1 子組件Child.vue

<template>
	<div>我是子組件</div>
</template>
 
<script setup>
// 第一步:定義子組件的方法
const sayHello = (value) => {
	console.log(value)
}
// 第二部:暴露方法
defineExpose({
	sayHello 
})
</script>

3.2 父組件Father.vue

<template>
	<button @click="getChild">觸發(fā)子組件方法</button>
	<child ref="childRef" />
</template>
<script setup>
import Child from './components/child.vue'
// 定義與 ref 同名變量
const childRef = ref(null)
const getChild = () => {
	// 調(diào)用子組件的方法或者變量,通過value
	childRef.value.hello("hello world!");
}
</script>

4、簡單說下選項(xiàng)式API的寫法

不推薦,vue3能寫組合式就寫組合式

4.1 父組件 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.title;
      //執(zhí)行了子組件的 play方法
      this.$refs.childComp.play();
    },
  },
};
</script> 

4.2 子組件 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>

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

相關(guān)文章

最新評論

昌乐县| 平凉市| 肇源县| 中阳县| 蛟河市| 恭城| 赞皇县| 舟曲县| 南部县| 博爱县| 石首市| 南岸区| 新民市| 苗栗县| 茶陵县| 柘城县| 西平县| 青州市| 盐城市| 武邑县| 桂平市| 女性| 英山县| 旌德县| 兴隆县| 桂阳县| 新乐市| 乐清市| 巫溪县| 广灵县| 安徽省| 彩票| 溧阳市| 定西市| 手游| 阜阳市| 清水县| 武夷山市| 南投县| 兴隆县| 葫芦岛市|