一 父---> 子 組件通信
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; // 接收
});
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。