面试题
2.1 Vue子组件可以直接改变父组件的数据吗?
首先写一个父子传参的案例
父组件的内容:
<template> <div> <Children :fromParentMsg="toChildMsg" @fromParent="getChildMsg"></Children> </div></template><script>import Children from './Children.vue'export default { components: { Children }, data() { return { toChildMsg: '传给子组件的数据', } }, methods: { getChildMsg(val) { console.log(`获取到了从子组件获取的参数:${val}`) }, },}</script><style lang="scss" scoped></style>
子组件的内容:
<template> <div> <h3>从父组件获取的值是:{{ fromParentMsg }}</h3> <button @click="toParent">传值给父组件</button> </div></template><script>export default { name: 'Children', props: { fromParentMsg: { type: String, default: '', }, }, data() { return { fomrChildMsg: '我是子组件的数据', } }, methods: { toParent() { this.$emit('fromParent', this.fomrChildMsg) }, },}</script><style lang="scss" scoped></style>
结果展示:
子组件获得了父组件传的值
点击按钮,父组件获得了子组件传的值
这里有一个问题:假如父组件也传递了参数
@fromParent="getChildMsg(id)"
如此,就接收不到子组件传递的数据了。获得了两个undefined
此时需要给绑定的函数传递第二个固定参数(事件对象):$event:
@fromParent="getChildMsg(id,$event)"
但是只能获取一个参数,如果有多个参数,可以封装到对象中传递;
Vue子组件可以直接改变父组件的数据吗?
子组件不可以直接改变父组件的数据。这样做主要是为了维护父子组件的单项数据流,每次父级组件发生更新时,子组件中所有的prop都将会刷新为最新的值。
Vue提倡单项数据流,即父级props的更新会流向子组件,但是反过来则不行。这是为了防止意外的改变父组件的状态,使应用数据流变得难以理解,导致数据流混乱。只能通过 $emit 派发的自定义事件,父组件接收后,由父组件修改。