vue组件传值子父、父子、兄弟vue组件传值分三类:1.父 ----子.子—父3.兄弟—兄弟.父向子传值用props,3步解决:在子组件props属性中随便取个名字,我取了cvalue在父组件中引入子组件将刚才取的随便的名字绑定个值这个值名字我取了value为父组件的data这个是父组件的data的value的值绑定好了就可以肆意的在子组件中使用啦,这里cvalue的值就是父组件data中value的值附上例子代码!DOCTYPEhtmlhtml langenheadmeta charsetUTF-8meta nameviewportcontentwidthdevice-width, initial-scale1.0meta http-equivX-UA-Compatiblecontentieedge!--vue--script srchttps://cdn.jsdelivr.net/npm/vue2.5.16/dist/vue.js/scripttitleDocument/title/headbodydiv idfatherchild:cvaluevalue/child/div/bodytemplate idchildh1{{cvalue}}/h1/templatescriptvarvmnewVue({el:#father,data:{value:这是父组件的data},components:{child:{template:#child,props:[cvalue]}}})/script/html2.子向父传值用$emit,3步解决:在子组件创建个方法用$emit事件名称要传递的值注册事件.ps:可以理解为何click一样触发时执行定义的函数在子组件定义什么时候触发事件这里我写的是当点击h1的时候tofather事件被触发.在父组件对tofather事件进行绑定触发的时候要干啥我这里调用了个方法把触发时的值this.cvalue作为参数传了进去,注意参数必须写event因为事件响应传过来的值是用event因为事件响应传过来的值是用event因为事件响应传过来的值是用event接收滴下图为我定义的父组件getvalue的方法这里的形参可以随便取附上例子代码!DOCTYPEhtmlhtml langenheadmeta charsetUTF-8meta nameviewportcontentwidthdevice-width, initial-scale1.0meta http-equivX-UA-Compatiblecontentieedge!--vue--script srchttps://cdn.jsdelivr.net/npm/vue2.5.16/dist/vue.js/scripttitleDocument/title/headbodydiv idfatherchild tofathergetvalue($event)/child/divtemplate idchildh1 clickonclick这个是子组件{{cvalue}}/h1/template/body/htmlscriptvarvmnewVue({el:#father,data:{value:这是父组件的data},methods:{getvalue($event){alert(这个是子组件传递过来的值$event)}},components:{child:{template:#child,data(){return{cvalue:这是子组件的值}},methods:{onclick(){this.$emit(tofather,this.cvalue)}},}}})/script3.兄弟传值子子传值方法先子传父再父传子小型项目可以这么搞方法用vuex,3步解决;ps:vuex相当于一个仓库或者说是数据库创建之后你可以随时的对这个仓库里的数据进行改查vuex:4个属性:state:存放数据;getters:查询数据;mutation:修改数据action:异步运行mutation.创建vuex仓库:组件里要传的值放入仓库我把data中的msg放入仓库记得声明sotre属性第二个store为所创建的Vuex.Store实例,我定义了个方法绑定了个点击事件调用方法当点击h2时调用senMsg把仓库里msg的值设置为组件中的msg的值3. 组件2中把仓库中的msg的值设置为计算属性当上面点击h2时组件修改仓库里msg的值组件获取到仓库中msg的值就完成了组件向组件传值附上例子代码!DOCTYPEhtmlhtml langenheadmeta charsetUTF-8meta nameviewportcontentwidthdevice-width, initial-scale1.0meta http-equivX-UA-Compatiblecontentieedge!--vue--script srchttps://cdn.jsdelivr.net/npm/vue2.5.16/dist/vue.js/scriptscript srchttps://cdn.bootcss.com/vuex/3.0.1/vuex.min.js/scripttitleDocument/title/headbodydiv idfathersyb1/syb1syb2/syb2/div/bodytemplate idsyb1divh1这是兄弟1/h1h2 clicksendMsg{{msg}}/h2/div/templatetemplate idsyb2divh1这是兄弟2/h1h1{{getMsg}}/h1/div/templatescriptvarstorenewVuex.Store({state:{msg:这个是存在vuex里的值:},getters:{getMsg(state){returnstate.msg}},mutations:{setMsg(state,msg){state.msgmsg}},actions:{setMsg(content){content.commit(setMsg,msg)}}})varvmnewVue({el:#father,data:{value:这是父组件的data,},created(){console.log(this.$store)},components:{syb1:{template:#syb1,data(){return{msg:这是兄弟1的消息}},methods:{sendMsg(){this.$store.commit(setMsg,this.msg)}},store:store},syb2:{template:#syb2,data(){return{}},computed:{getMsg(){returnthis.$store.state.msg}},store:store}}})/script/html