时间:2023-02-23 09:10:51 | 栏目:vue | 点击:次
需求:把Login.vue的username传到Index.vue中显示出来
Login.vue
登录后跳转
store.js
定义变量并从Login.vue中获取值
Index.vue
定义变量,利用computed获取变量的值
然后新建一个对象var vue1=new Vue({}),利用vue1这个新对象作为中介传值,
然后用 vue1.$emit("isa",this.aaa) 即把this.aaa赋给isa
methods:{ tapa(){ vue1.$emit("isa",this.aaa) } }
用 $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>