共计 1722 个字符,预计需要花费 5 分钟才能阅读完成。
父组件 >> 子组建
使用 prop
父组件 Parent.vue
<template> | |
<div> | |
<child :msg='toChildMsg'></child> | |
</div> | |
</template> |
export default {data() { | |
return {toChildMsg: 'message',}, | |
}, | |
} |
子组件 Child.vue
<template> | |
<div> | |
{{msg}} | |
</div> | |
</template> |
export default { | |
props: { | |
msg: String, // 这里是传递参数的类型 | |
default: '默认值', // 这里是默认值 | |
}, | |
} |
子 >> 父
事件派发
子组件 Child.vue
<template> | |
<div> | |
<button @click='changeParentData'><button> | |
</div> | |
</template> |
export default { | |
methods: {changeParentData() {this.$emit('change', '来自子组件的消息'); | |
}, | |
}, | |
} |
父组件 Parent.vue
<template> | |
<div> | |
<child :change='changeData'></child> | |
</div> | |
</template> |
export default {data() { | |
return {parentData: '',}, | |
}, | |
methods: {changeData(val) { | |
// val 是子组件传递过来的值 | |
this.parentData = val; // 事件派发修改 data | |
}, | |
}, | |
} |
当然每次为了修改一条数据就定义一个方法有点繁琐,Vue 在 2.4+ 的版本中加了一个语法糖 .sync
修饰符
下面放用法
子组件 Child.vue
<template> | |
<div> | |
<button @click='changeParentData'><button> | |
</div> | |
</template> |
export default { | |
methods: {changeParentData() {this.$emit('update:parentData', '来自子组件的消息'); | |
}, | |
}, | |
} |
父组件 Parent.vue
<template> | |
<div> | |
<child :parentData.sync='parentData'></child> | |
</div> | |
</template> |
export default {data() { | |
return {parentData: '',}, | |
}, | |
} |
父 >> 孙
使用 provide
和inject
祖先组件 Parent.vue,这里我们将父组件的 vue 实例对象传递出去
export default {provide() { | |
return {pVue: this,}; | |
}, | |
data() { | |
return: {pMsg: '祖先组件 data',} | |
} | |
}; |
子孙组件 Grandson.vue,接受祖先组件的实例对象,就可以使用 Parent.vue 中的方法和数据了
<template> | |
<div> | |
{{pVue.pMsg}} | |
</div> | |
</template> |
export default {inject: ['pVue'], | |
}; |
两两不相关的组件
通过事件总线来传递参数
在main.js
中定义一个传递参数的中间件$bus
main.js
const bus = new Vue(); | |
Vue.prototype.$bus = bus; |
A.vue
<template> | |
<div> | |
<button @click="change"> 改变 B 组件的参数 </button> | |
</div> | |
</template> |
export default { | |
methods: {change() {this.$bus.$emit('changeB', '修改 B 组件的参数'); | |
} | |
} | |
}; |
B.vue
export default {data() { | |
return {data: '等待被修改',}; | |
}, | |
created() { | |
// 监听 change 事件修改组件内部的参数 | |
this.$bus.$on('changeB', msg => {this.data = msg;}) | |
} | |
}; |
当然如果有很多数据需要维护,不停的依靠组件通信也是一件不太优雅的事情,这个时候就可以依赖vuex
,当我们仅仅需要简单的通信,以上的方法就可以解决大部分问题.
正文完