欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

vue3子組件之間相互傳值

1、引用第三方庫mitt

npm install mitt

2、在項目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不同組件之間相互傳值

使用一個空Vue實例來進行傳值,通過$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>

總結

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

相關文章

最新評論