vue的组件传值
①父组件传值给子组件(props)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<lq-dad></lq-dad>
</div>
</body>
<script type='text/javascript' src='../js/vue.js'></script>
<script type='text/javascript'>
let LqSon = Vue.component('lq-son',{
props:['number'],
template:`
<div>接收到爸爸的通知是{{number}}</div>
`
})
Vue.component('lq-dad',{
data(){
return{
number:1
}
},
template:`
<div>{{number}}<lq-son :number = 'number'></lq-son></div>
`,
methods:{
send(){
}
},
components:{
"lq-son":LqSon
}
})
new Vue({
el: "#app",
data: {
},
})
</script>
</html>
②子组件给父组件传值($emit派发)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<lq-dad ></lq-dad>
</div>
</body>
<script type='text/javascript' src='../js/vue.js'></script>
<script type='text/javascript'>
let LqSon = Vue.component('lq-son', {
data(){
return{
num:1
}
},
template: `
<div><button @click = 'send'>给爸爸的通知是{{num}}</button></div>
`,
methods:{
send(){
console.log(this.num)
this.$emit('val',this.num)
}
}
})
Vue.component('lq-dad', {
data(){
return{
num:''
}
},
template: `
<div>接收到儿子的值是{{num}}<lq-son @val="vall"></lq-son></div>
`,
components: {
"lq-son": LqSon
},
methods:{
vall(ea){
this.num = ea
console.log(ea)
}
}
})
new Vue({
el: "#app",
data: {
},
})
</script>
</html>
③兄弟组件传值(on接收)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<brother-one></brother-one>
<brother-two></brother-two>
</div>
</body>
<script type='text/javascript' src='../js/vue.js'></script>
<script type='text/javascript'>
var bus = new Vue()
Vue.component('brother-one',{
data(){
return {
num:0
}
},
template:`<div>我是哥哥{{num}} <button @click='send'>to 小弟</button></div>`,
methods:{
send(){
bus.$emit('accept',this.num)
}
}
})
Vue.component('brother-two',{
data(){
return {
num:''
}
},
template:`<div>我是弟弟,哥哥给我了{{num}}</div>`,
mounted(){
bus.$on('accept',(val)=>{
this.num = val
})
}
})
new Vue({
el:'#app',
data:{
}
})
</script>
</html>