vue如何利用store實(shí)現(xiàn)兩個(gè)平行組件間的傳值
store實(shí)現(xiàn)兩個(gè)平行組件間的傳值
需求:把Login.vue的username傳到Index.vue中顯示出來

方法:利用store.js傳值
Login.vue

登錄后跳轉(zhuǎn)

store.js
定義變量并從Login.vue中獲取值

Index.vue
定義變量,利用computed獲取變量的值


平行組件傳值的步驟
1.布好局
然后新建一個(gè)對象var vue1=new Vue({}),利用vue1這個(gè)新對象作為中介傳值,
然后用 vue1.$emit("isa",this.aaa) 即把this.aaa賦給isa
?methods:{
? ? ? ? ? ? ? tapa(){
? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? ? ?vue1.$emit("isa",this.aaa)
? ? ? ? ? ? ? ?}
? ? ?}2.在ccc模板中用mounted函數(shù)接收
用 $on( "isa",function(msg){ msg即為接收isa的值 })
? ? ? ? ? ? ?mounted() {
? ? ? ? ? ? ? ? ? ? var that = this;
? ? ? ? ? ? ? ? ? ? vue1.$on("isa",function(msg1){
? ? ? ? ? ? ? ? ? ? ? ? that.isa=msg1
? ? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? ? ? ? vue1.$on("isb",function(msg2){
? ? ? ? ? ? ? ? ? ? ? ? that.isb=msg2
? ? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? ? },完整代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="../vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<h1>平行組件</h1> <hr>
<v-a></v-a> <hr>
<v-b></v-b> <hr>
<v-c></v-c> <hr>
</div>
<template id="aaa">
<div>
<h1>aaaa</h1>
<h3>{{aaa}}</h3>
<button @click="tapa()">a給CCC傳值</button>
</div>
</template>
<template id="bbb">
<div>
<h1>bbbb</h1>
<h3>{{bbb}}</h3>
<button @click="tapb()">b給CCC傳值</button>
</div>
</template>
<template id="ccc">
<div>
<h1>cccc</h1>
<h3>aaaa值:{{isa}}</h3>
<h3>bbbb值:{{isb}}</h3>
</div>
</template>
</body>
<script>
var vue1=new Vue({})
var vue = new Vue({
el:"#app",
data:{
},
components:{
"v-a":{
template:"#aaa",
data:function (){
return {
aaa:"這是a的值"
}
},
methods:{
tapa(){
vue1.$emit("isa",this.aaa)
}
}
},
"v-b":{
template:"#bbb",
data:function (){
return {
bbb:"這是b的值"
}
},
methods:{
tapb(){
vue1.$emit("isb",this.bbb)
}
}
},
"v-c":{
template:"#ccc",
data:function (){
return {
isa:"",
isb:""
}
},
mounted() {
var that = this;
vue1.$on("isa",function(msg1){
that.isa=msg1
})
vue1.$on("isb",function(msg2){
that.isb=msg2
})
},
}
}
})
</script>
</html>以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
查看vue-cli腳手架的版本號和vue真實(shí)版本號及詳細(xì)操作命令
本文給大家分享如何查看vue-cli腳手架的版本號和vue真實(shí)版本號及詳細(xì)操作過程,本文給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2022-11-11
詳解用vue.js和laravel實(shí)現(xiàn)微信支付
本篇文章主要介紹了用vue.js和laravel實(shí)現(xiàn)微信支付,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
vue項(xiàng)目中圖片選擇路徑位置static或assets的區(qū)別及說明
這篇文章主要介紹了vue項(xiàng)目中圖片選擇路徑位置static或assets的區(qū)別及說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
vue項(xiàng)目查看vue版本及cli版本的實(shí)現(xiàn)方式
這篇文章主要介紹了vue項(xiàng)目查看vue版本及cli版本的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
原生JS?Intersection?Observer?API實(shí)現(xiàn)懶加載
這篇文章主要為大家介紹了原生JS?Intersection?Observer?API實(shí)現(xiàn)懶加載示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07

