在Vue中,父子组件的关系可以总结为prop向下传递,事件向上传递。
props
<template>
<!--通过props向子组件传递name值-->
<child name="小明"/>
</template>
<script>
// 引入子组件
import child from "./child-component"
export default {
name: "parent-component",
components:{
child
}
}
</script>
<style scoped>
</style>
<template>
<div>
通过props从父控件传递的值:{{name}}
</div>
</template>
<script>
export default {
name: "child-component",
props: {
name: {
type: String,
default: "xiaoming"
}
}
}
</script>
<style scoped>
</style>
子组件通过声明props变量,接收从父组件传递过来的值,当然props传递的值也可以是数组,对象或者是其他类型。
VUE的单向数据流中,父级 prop 的更新会向下流动到子组件中,但是反过来则不行。
$on(evntName)$emit(eventName,optionalPayload)
每个Vue实例都实现了事件接口:使用$on(evntName)
监听事件;使用$emit(eventName,optionalPayload)
触发事件。另外,父组件可以在使用子组件的地方直接用v-on来监听子组件触发的事件
<template>
<div style="background-color: #0a9dc7 ;height:200px">
通过props从父控件传递的值:{{name}}
<button @click="btnClick">向父组件传值</button>
</div>
</template>
<script>
export default {
name: "child-component",
props: {
name: {
type: String,
default: "xiaoming"
}
},
data() {
return {
user: {
name: "xieluoxixi",
password: "123456"
},
other: "other data"
}
},
methods: {
btnClick() {
//通过$emit向父组件传递值,其中可以一次性传递多个
this.$emit("sendEventToParent", this.user, this.other)
}
}
}
</script>
<style scoped>
</style>
<template>
<div>
<p>
父组件从子组件上获取的值:
{{user.name+user.password}}
{{other}}
</p>
<!--通过props向子组件传递name值-->
<p>
下方为子组件区域
</p>
<child name="小明" @sendEventToParent="getValueFromChild"/>
</div>
</template>
<script>
// 引入子组件
import child from "./child-component"
export default {
name: "parent-component",
components: {
child
},
data() {
return {
//用于接收从子组件传递回来的值
user: {},
other: ""
}
},
methods: {
getValueFromChild(user, other) {
// console.log(user)
// console.log(other)
this.user = user
this.other = other
}
}
}
</script>
<style scoped>
</style>
<!-- 引入子组件 定义一个on的方法监听子组件的状态-->
<child v-on:childByValue="childByValue"></child>
methods: {
childByValue: function (childValue) {
// childValue就是子组件传过来的值
this.name = childValue
}
}
}
父组件: 在子组件中加上ref即可通过this.$refs.method调用
<template>
<div @click="parentMethod">
<children ref="c1"></children>
</div>
</template>
<script>
import children from 'components/children/children.vue'
export default {
data(){
return {
}
},
computed: {
},
components: {
'children': children
},
methods:{
parentMethod() {
console.log(this.$refs.c1) //返回的是一个vue对象,可以看到所有添加ref属性的元素
this.$refs.c1.childMethods();
}
},
created(){
}
}
</script>
4.可以通过$parent
和$children
获取父子组件的参数
我们可以使用$children[i].paramsName
来获取某个子组件的属性值或函数,$children
返回的是一个子组件数组
那么子组件怎么获取修改父组件的数据内容?这需要使用$parent
this.parentMsg = this.$children[1].childMsg
vue 全局事件(eventBus)
在main.js里:window.eventBus = new Vue();//注册全局事件对象
兄弟之间的传值用Vuex
在state
里定义数据和属性
在 mutations
里定义函数fn
,在页面通过this.$store.commit('fn',params)
来触发函数