vue.js 组件数据传递
一 父---> 子 组件通信
1,声明一个组件(props 指定组件外来接受的参数,我指定了一个string类型的message参数,默认内容为‘I Am AESCR’)
Vue.component('test-com',{ props:{ message:{ type:String, default:'I Am AESCR' } }, template:'<div>{{message}}</div>' })<div id="app"> <test-com message='边学边记'></test-com></div>
2,把需要传递的内容直接写在组件属性上面,通过v-bind:形式绑定,传递内容就变得容易修改了
<div id="app"> <input type="text" v-model='msg' placeholder="请输入内容"/> <test-com v-bind:message='msg'></test-com></div><script> Vue.component('test-com',{ props:{ message:{ type:String, default:'默认信息' } }, template:'<div>{{message}}</div>' }) new Vue({ el:'#app', data:{ msg:'I an AESCR' } })</script>
二 子 --->父组件数据传递
1,通过触发事件的方式来传递数据,我们先说明一个组件,和一个事件
Vue.component('test-com',{ data:function(){ return{ msg:'I am AESCR' } }, methods: { hello:function(){ this.$emit('sayhello',this.msg) #sayhello 为组件上监听的事件名称一致,后面为参数 } }, template:'<div><input type="button" v-on:click="hello()" value="打招呼" /><input type="text" v-model="msg"/></div>' }) 调用组件 <div id="app2"> <p>外层 {{content}}</p> <test-com v-on:sayhello='sayhellocontent'></test-com> #sayhellocontent为外层事件名称 </div> new Vue({ el:'#app2', data:{ 'content':null, }, methods:{ sayhellocontent:function(content){ #content会接受到$emit传递的参数 this.content=content } } })
三 组件间传递数据
1.新建一个js文件,然后引入vue 实例化vue 最后暴露这个实例2.在要广播的地方引入刚才定义实例3.通过vueEmit.$emit('名称',‘数据’)4.在接收数据 ---------------------------------------------------Vue.$on('名称',function(){})我们可以实例化一个vue实例,相当于一个第三方let vm = new Vue(); //创建一个新实例<div @click="ge"></div>methods: { ge() { vm.$emit('blur','sichaoyun'); //触发事件 传递参数 }}组件接受created() { vm.$on('blur', (arg) => { this.test= arg; // 接收 });}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。