父子组件之间的传值

父组件通过属性的方式向子组件传值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<body>
<div id="root">
<counter :count="0"></counter>
<counter :count="2"></counter>
</div>
<script>
// 定义局部组件
var counter={
props:['count'],
template:'<div @click="handle">{{count}}</div>',
methods:{
handle:function(){
this.count++
}
}
}
var vm=new Vue({
el:'#root',
components:{ //在父组件中使用局部组件要先在父组件中注册
counter:counter
},
data:{
}
})
</script>
</body>

此时会出现警告

单向数据流

这关系到Vue中单向数据流的概念:父组件可以向子组件传递参数(通过属性的方式),但子组件绝对不能去修改父组件传递过来的参数,只能通过定义自己的变量去接收到父组件的值,再修改自己的变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>
// 定义局部组件
var counter={
//接收父组件的count值
props:['count'],
template:'<div @click="handle">{{number}}</div>',
//定义我自己的number
data:function(){
return {
number:this.count
}
},
methods:{
handle:function(){
//可以随意修改自己组件内的值
this.number++
}
}
}
var vm=new Vue({
el:'#root',
components:{
counter:counter
},
data:{
}
})
</script>

this.$emit(‘change’)

子组件向父组件通过事件的形式传值,通过this.$emit(‘change’)向外触发change事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<body>
<div id="root">
<counter :count="0" @change='handlechange'></counter>
<counter :count="0" @change='handlechange'></counter>
<div>{{total}}</div>
</div>
<script>
// 定义局部组件
var counter={
//接收父组件的count值
props:['count'],
template:'<div @click="handle">{{number}}</div>',
//定义我自己的number
data:function(){
return {
number:this.count
}
},
methods:{
handle:function(){
//可以随意修改自己组件内的值
this.number+=2;
this.$emit('change',2) //步长为2,增量为2
}
}
}
var vm=new Vue({
el:'#root',
components:{
counter:counter
},
data:{
total:0
},
methods:{
handlechange:function(step){
this.total+=step
}
}
})
</script>
</body>

组件参数校验

props


首先这是正常的组件参数的传值,我们可以对props里的内容修改,从而实现参数校验功能

1
2
3
props:{
content:[String ,Number] //允许传入的参数为字符串和数字类型
},

更复杂的校验:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<body>
<div id="root">
<my content="hello Vue"></my>
</div>
<script>
Vue.component('my',{
props:{
content:{
type:String,
required:true, //是否必需传值,true:不传就会报错
default:"default value", //不传值时,会有默认值
validator:function(value){ //content的自定义校验器
return (value.length<5) //content的长度应小于5,否则报错
}
}
},
template:'<div>{{content}}</div>'
})
var vm=new Vue({
el:'#root'
})
</script>
</body>

请我喝杯咖啡吧~

支付宝
微信