vue组件化通信之子向父传值
vue组件化通信之兄弟组件传值
父向子组件传值
常用的方法主要有三种:props、$refs、$children 建议使用前两种
使用props进行传值
parent.vue
<template>
<div>
<childTest :msg='msg'></childTest>
</div>
</template>
<script>
import childTest from './childTest.vue'
export default {
components:{
childTest
},
data() {
return{
msg: 'my vue'
}
}
}
</script>
childTest.vue
<template>
<div>
<h1>{{msg}}</h1>
</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
default: ''//默认值
}
}
}
</script>
使用$refs进行传值
parent.vue
<template>
<div>
<childTest ref='child'></childTest>
</div>
</template>
<script>
import childTest from './childTest.vue'
export default {
components:{
childTest
},
mounted() {
this.$refs.child.msg = 'my vue rfs'
}
}
</script>
childTest.vue
<template>
<div>
<h1>{{msg}}</h1>
</div>
</template>
<script>
export default {
data(){
return{
msg: ''
}
}
}
</script>
使用$children进行传值
parent.vue
<template>
<div>
<childTest></childTest>
</div>
</template>
<script>
import childTest from './childTest.vue'
export default {
components: {
childTest
},
mounted() {
/*
当前实例的直接子组件。需要注意 $children 并不保证顺序,也不是响应式的。如果 你发现自己正在尝试使用 $children 来进行数据绑定,考虑使用一个数组配合 v-for 来生成子组件,并且使用 Array 作为真正的来源。
*/
this.$children[0].msg = 'my vue $children'
}
}
</script>
childTest.vue
<template>
<div>
<h1>{{msg}}</h1>
</div>
</template>
<script>
export default {
data(){
return{
msg: ''
}
}
}
</script>