1.父传子
1.v-bind(:)传值,props接收
2.$ref
props 是单向绑定的,子组件只能接收
props: {
// fooA只接受数值类型的参数
fooA: Number,
// fooB可以接受字符串和数值类型的参数
fooB: [String, Number],
// fooC可以接受字符串类型的参数,并且这个参数必须传入
fooC: {
type: String,
required: true
},
// fooD接受数值类型的参数,如果不传入的话默认就是100
fooD: {
type: Number,
default: 100
},
// fooE接受对象类型的参数
fooE: {
type: Object,
// 当为对象类型设置默认值时必须使用函数返回
default: function() {
return { message: "Hello, world" };
}
},
// fooF使用一个自定义的验证器
fooF: {
validator: function(value) {
return value >= 0 && value <= 100;
}
},
fooG: {
type:Array,
// 当为数组类型设置默认值时必须使用数组返回
default: function() {
return [];
}
},
}
prop 着重于数据的传递,它并不能调用子组件里的属性和方法。像创建文章组件时,自定义标题和内容这样的使用场景,最适合使用prop。
$ref 着重于索引,主要用来调用子组件里的属性和方法,其实并不擅长数据传递。而且ref用在dom元素的时候,能使到选择器的作用,这个功能比作为索引更常有用到。
2.子传父(传方法)
v-on传值
$emit接收
//父组件
<thrid @cc="cc"></thrid>
cc (msg) {
alert(msg)
},
//子组件
<template>
<div>
<div @click="cc(msg)">子传父</div>
</div>
</template>
<script>
export default {
name: 'tried',
data () {
return {
msg: '子组件的数据'
}
},
methods: {
cc () {
this.$emit('cc', this.msg)
}
}
}
</script>
3.兄弟组件传
新建一个bus.js用来中转
import Vue from 'vue'
export default new Vue()
//组件分别引用bus.js
import Bus from '../bus'
//第一个
<div @click="bb">发送</div>
methods: {
bb () {
Bus.$emit('val', 'aaaaaaaa')
}
}
//第二个
<span>{{name}}</span>
mounted () {
Bus.$on('val', (data) => {
console.log(data)
this.name = data
})
}







网友评论