[Vue框架学习笔记]父子组件间的三种通信方式(有实例,速来!) |
您所在的位置:网站首页 › vue通信的几种方法 › [Vue框架学习笔记]父子组件间的三种通信方式(有实例,速来!) |
父子组件间的三种通信方式
通过props实现通信props静态传递father_props.vuechild_props.vue
props动态传递father_props.vuechild_props.vue 子组件不变
通过$ref实现通信father_ref.vuechild_ref.vue
props和$ref的对比$emit实现通信father_emit.vuechild_emit.vue
总而言之,说一下三种方法
通过props实现通信
子组件的props选项能够接收来自父组件的数据。props是单项绑定的 props静态传递子组件通过props选项来声明一个自定义的属性,然后父组件就可以再嵌套标签的时候,通过这个属性往子组件传递数据了! father_props.vue 我是父组件! import Child from '../components/child_props.vue' export default { components: { Child } } child_props.vue {{ message }} export default { props: ['message'] // 声明一个自定义的属性 }更多的时候我们需要传送一个动态的数据。这时候就可以用==v-bind(:)==实现。通过v-bind绑定props的自定义的属性,传递过去的就不是静态的字符串了,它可以是一个表达式,布尔值,对象等等任何类型的值 father_props.vue 我是父组件! import Child from '../components/child_props.vue' export default { components: { Child }, data () { return { a: '我是子组件二!', b: 41, msg: '我是子组件三!' + Math.random() } } } child_props.vue 子组件不变对于ref官方的解释是:ref是被用来给元素或子组件注册引用信息的。引用信息将会注册在父组件的$refs对象上。 props是父组件给子组件信息,那么, $ref就是子组件给父组件信息。 简单来说,父组件可以通过$ref来调用子组件的信息,包括data和methods father_ref.vue 我是父组件! import Child from '../components/child_ref.vue' export default { components: { Child }, mounted: function () { console.log(this.$refs.msg) this.$refs.msg.getMessage('我是子组件一!') } } child_ref.vue {{ message }} export default { data () { return { message: '' } }, methods: { getMessage (m) { this.message = m } } }上面两种方法主要都是父组件为主,给子组件信息,调用子组件的信息。 那么,第三种方法就是以子组件为主。 $emit绑定一个自定义事件event,当这个语句被执行的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。 father_emit.vue {{ title }} import Child from '../components/child_emit.vue' export default { components: { Child }, data () { return { title: '' } }, methods: { showMsg (title) { this.title = title } } } child_emit.vue 我是子组件! export default { mounted: function () { this.$emit('getMessage', '我是父组件!') } } |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |