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

vue3實(shí)戰(zhàn)-子組件之間相互傳值問題

 更新時(shí)間:2023年03月19日 15:33:46   作者:月影星云  
這篇文章主要介紹了vue3實(shí)戰(zhàn)-子組件之間相互傳值問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

vue3子組件之間相互傳值

1、引用第三方庫(kù)mitt

npm install mitt

2、在項(xiàng)目src文件夾下創(chuàng)建utils文件夾,在utils創(chuàng)建mitt.js,mitt.js中的代碼如下:

import mitt from "mitt";
export default new mitt();

3、示例:組件A傳值給組件B

//在組件A中引入
import mitt from "@/utils/mitt";

//調(diào)用傳值
mitt.emit("mittClick", "數(shù)據(jù)數(shù)據(jù)數(shù)據(jù)");
//在組件B中引入
import mitt from "@/utils/mitt";

//接收傳值
mitt.on("mittClick", (val) => {
?? ?console.log(val)//數(shù)據(jù)數(shù)據(jù)數(shù)據(jù)
})

vue不同組件之間相互傳值

使用一個(gè)空Vue實(shí)例來(lái)進(jìn)行傳值,通過$emit,$on即可。

<!DOCTYPE html>
<html lang="zh-CN">
? ? <head>
? ? ? ? <title></title>
? ? ? ? <meta charset="utf-8">
? ? ? ? <script src="./main/vue.js"></script>
? ? </head>
? ? <body>
? ? ? ? <div id="demo">
? ? ? ? ? ? <!-- test code -->
? ? ? ? ? ? <custom-a></custom-a>
? ? ? ? ? ? <custom-b></custom-b>
? ? ? ? ? ? <!-- test code -->
? ? ? ? </div>
? ? </body>
? ? <script type="text/javascript">
? ? let bus = new Vue();
? ? Vue.component("custom-a", {
? ? ? ? template: '<button @click="transValue">Click</button>',
? ? ? ? methods: {
? ? ? ? ? ? transValue: () => bus.$emit("transValue", "hello from a")
? ? ? ? }
? ? });
? ? Vue.component("custom-b", {
? ? ? ? template: '<input :value="msg">',
? ? ? ? data: function() {
? ? ? ? ? ? return {
? ? ? ? ? ? ? ? msg: ""
? ? ? ? ? ? }
? ? ? ? },
? ? ? ? mounted() {
? ? ? ? ? ? bus.$on("transValue", msg => this.msg = msg)
? ? ? ? }
? ? });
? ? new Vue({
? ? ? ? el: "#demo"
? ? });
? ? </script>
</html>

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論