美文网首页
Vue 组件间通信

Vue 组件间通信

作者: 最尾一名 | 来源:发表于2018-12-22 14:55 被阅读0次

    背景

    在使用 Vue 时,经常会有父子组件之间的通信需求,有很多种方法可以实现。


    实现

    父组件向子组件通信

    方法一: 使用 $children

    $children

    方法二:使用 props

    通过 props 选项 ,父组件可以将数据传递给子组件。

    // father.vue
    <template>
        <child :msg="message"></child>
    </template>
    
    <script>
    
    import child from './child.vue';
    
    export default {
        components: {
            child
        },
        data () {
            return {
                message: 'father message';
            }
        }
    }
    </script>
    
    // child.vue
    <template>
        <div>{{msg}}</div>
    </template>
    
    <script>
    export default {
        props: {
            msg: {
                type: String,
                required: true
            }
        }
    }
    </script>
    

    子组件向父组件通信

    方法一:使用 $parent

    $parent

    方法二:通过修改父组件传递的 props 来修改父组件数据(不推荐)

    方法三:通过 Vue 事件传递数据

    父组件向子组件传递事件方法,子组件通过 $emit 触发事件,回调给父组件。

    // father.vue
    <template>
        <child @msgFunc="func"></child>
    </template>
    
    <script>
    
    import child from './child.vue';
    
    export default {
        components: {
            child
        },
        methods: {
            func (msg) {
                console.log(msg);
            }
        }
    }
    </script>
    
    // child.vue
    <template>
        <button @click="handleClick">点我</button>
    </template>
    
    <script>
    export default {
        props: {
            msg: {
                type: String,
                required: true
            }
        },
        methods () {
            handleClick () {
                //........
                this.$emit('msgFunc');
            }
        }
    }
    </script>
    

    非父子组件、兄弟组件之间的数据传递

    非父子组件通信,Vue 官方推荐使用一个 Vue 实例作为中央事件总线

    Vue 内部有一个事件机制,可以参考源码

    $on 方法用来监听一个事件。

    $emit 用来触发一个事件。

    复杂的单页应用数据管理

    使用 vuex 来进行数据的管理。


    参考

    https://github.com/answershuto/learnVue/blob/master/docs/Vue%E7%BB%84%E4%BB%B6%E9%97%B4%E9%80%9A%E4%BF%A1.MarkDown

    相关文章

      网友评论

          本文标题:Vue 组件间通信

          本文链接:https://www.haomeiwen.com/subject/oomikqtx.html