子組件向父組件傳值
1.在子組件中定義一個(gè)事件
2.在事件中通過(guò)$emit
方法傳遞數(shù)據(jù)
3.在父組件中注冊(cè)通過(guò)$emit
定義的事件
4.通過(guò)父組件中注冊(cè)的事件獲取到數(shù)據(jù)
$emit(name,data)
;
作用:注冊(cè)一個(gè)自定義事件,并發(fā)送數(shù)據(jù)
name:表示自定義事件
data:表示要發(fā)送的數(shù)據(jù)
<body>
<div id="app">
<test @toparent="getson"></test>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var test = {
template:`
<ul>
<li @click="getIndex(index)" v-for="(val,index) in list">{{val}}</li>//在子組件中定義一個(gè)事件
</ul>
`,
data:function(){
return{
list:['html','css','js']
}
},
methods:{
getIndex(index){
console.log({index});
this.$emit("toparent",[index,this.list]);//在事件中通過(guò)$emit方法傳遞數(shù)據(jù)
}
}
}
new Vue({
el:"#app",
components:{
test //在父組件中注冊(cè)通過(guò)$emit定義的事件
},
methods:{
getson(res){
console.log(res)//通過(guò)父組件中注冊(cè)的事件獲取到數(shù)據(jù)
}
}
})
</script>
</body>
父組件向子組件傳值
1.用props
屬性給組件聲明一個(gè)自定義屬性
2.在父組件中調(diào)用子組件,通過(guò)上一步聲明的自定義屬性來(lái)傳遞參數(shù)
<body>
<div class="test">
<tab :title="titleArr" :list="contList"></tab>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component("tab",{
props:['title','list'],
template:`
<div :style="objhead">
<div :style="clearFloat">
<div :style="hContent">{{title[0]}}</div>
<div :style="hContent">{{title[1]}}</div>
<div :style="hContent">{{title[2]}}</div>
</div>
<ul>
<li :style="clearFloat" v-for="val in list" >
<div :style="hContent" >{{val.name}}</div>
<div :style="hContent" >{{val.price}}</div>
<div :style="hContent" >{{val.num}}</div>
</li>
</ul>
</div>`,
data:function(){
return{
objhead:{
width:'600px',
background:"#eee",
},
hContent:{
float:"left",
width:"33.33%",
lineHeight:"35px",
textAlign:"center"
},
clearFloat:{
overflow:"hidden"
}
}
}
})
var vmTest = new Vue({
el:'.test',
data:{
titleArr:['商品名','價(jià)格','數(shù)量'],
contList:[{
name:"青菜",
price:12,
num:1
}]
}
})
</script>
</body>
子組件之間傳值
//借助另一個(gè)實(shí)例化對(duì)象發(fā)送
var app = new Vue()
var test1 = {
template:"<div @click='tos'>{{msg}}</div>",
data:function(){
return{
msg:"我是組件1的數(shù)據(jù)"
}
},
//必須通過(guò)事件發(fā)送,不能用鉤子函數(shù)
methods:{
tos(){
//新的實(shí)例化Vue對(duì)象
app.$emit('tosibling',this.msg);
}
}
}
var test2 = {
template:"<div>{{msg}}</div>",
data:function(){
return{
msg:"我是組件2的數(shù)據(jù)"
}
},
created(){
//新的實(shí)例化Vue對(duì)象
app.$on('tosibling',function(res){
console.log(res);
})
}
}
var vm = new Vue({
el:"#app",
components:{
test1,
test2
}
})