Vue父子组件相互通信三种方法

2018-08-15  本文已影响0人  马小帅mm

在vue中,我们经常会用到组件之间互相通信,父组件调用子组件的值,子组件调用父组件的值...
如果没有用到vuex,那么我们可以用什么方法来实现?

以下总结了几种方法:

1.使用事件机制,在父组件监听事件on, 在子组件调用事件emit(该方法适用于不是父子组件之间的通信)

父组件
<template>
    <div>
        <section>
            <children-components :options="parent_option"></children-components>
        </section>
    </div>
</template>

<script>
import childrenComponents from '@/components/test/ChildrenComponents';

export default {
    name: 'Index',
    components: {
        'children-components': childrenComponents
    },
    data () {
        return {
            parent_option: { input_value: 5 }
        }
    },
    mounted () {
        this.$event.on('change_value', e => {//注意this.$event.on方法就是对this.$on的封装
            this.parent_option = e.parent_option;
        });
        
    },
}
</script>
子组件
<template>
    <div>
        <input type="text" v-model="child_option.input_value"/>
    </div>
</template>

<script>
export default {
    name: 'ChildrenComponents',
    props: {
        options: { type: Object, required: true },
    },
    watch: {
        'child_option':{
        handler(newValue, oldValue) {
          this.$event.emit('change_value', {//注意this.$event.emit方法就是对this.$emit的封装
                    parent_option: newValue
                });
        },
        deep: true
      }
    },
    data(){
        return {
            child_option: { input_value: 6 }
        }
    }
}
</script>

2.父组件传值过去后子组件使用这个变量

父组件
<template>
    <div>
        <children-components :options="dcamera_option"></children-components>
    </div>
</template>

<script>
export default {
    name: 'index',
    components: {
        'children-components': childrenComponents
    },
    data(){
         dcamera_option: { input_value: 6 }
    }
}
</script>
子组件
<template>
    <div>
        <input type="text" v-model="options.input_value"/>
    </div>
</template>

<script>
export default {
    name: 'ChildrenComponents',
    props: {
        options: { type: Object, required: true },
    }
}
</script>

3.父组件传值过去后子组件调用这个变量

父组件
<template>
    <div>
        <children-components :options="dcamera_option"></children-components>
    </div>
</template>

<script>
export default {
    name: 'index',
    components: {
        'children-components': childrenComponents
    },
    data(){
         dcamera_option: { input_value: 6 }
    }
}
</script>
子组件
<template>
    <div>
        <input type="text" v-model="input_option.input_value" :change="chageValue()"/>
    </div>
</template>

<script>
export default {
    name: 'ChildrenComponents',
    props: {
        options: { type: Object, required: true },
    },
    data(){
        input_option: { input_value: 6 }
    },
    methods: {
        chageValue: function(){
            this.options.input_value = this.input_option.input_value;
        }
    }
}
</script>

end----------------------------

上一篇 下一篇

猜你喜欢

热点阅读