zoukankan      html  css  js  c++  java
  • Vue 组件通信

    父组件到子组件通信

    • 通过自定义属性传递
    //父组件:parent.vue
    <template>
        <div>
            <child :vals = "msg"></child>
        </div>
    </template>
    <script>
    import child from "./child";
    export default {
        data(){
            return {
                msg:"我是父组件的数据,将传给子组件"
            }
        },
        components:{
            child
        }
    }
    </script>
    
    //子组件:child.vue
    <template>
        <div>
            {{vals}}
        </div>
    </template>
    <script>
    export default {
          props:{ //父组件传值 可以是一个数组,对象
            vals:{
                type:String,//类型为字符窜
              default:"123" //可以设置默认值
            }
        },
    }
    </script>
    

    子组件到父组件通信

    • 使用 $emit(eventname,option) 触发事件
      • eventname:自定义事件名称,使用小写或-连接,不能使用驼峰写法
    • 子组件传递数据给父组件 (通过子组件内部的事件触发自定义事件$emit)
    //父组件:parent.vue
    <template>
        <div>
            <child  v-on:childevent='wathChildEvent'></child>
            <div>子组件的数据为:{{msg}}</div>
        </div>
    </template>
    <script>
    import child from "./child";
    export default {
        data(){
            return{
                msg:""
            }
        },
        components:{
            child
        },
        methods:{
            wathChildEvent:function(vals){//直接监听 又子组件触发的事件,参数为子组件的传来的数据
                console.log(vals);//结果:这是子组件的数据,将有子组件操作触发传给父组件
                this.msg = vlas;
            } 
        }
    }
    </script>
    
    //子组件:child.vue
    <template>
        <div>
           <input type="button" value="子组件触发" @click="target">
        </div>
    </template>
    <script>
    export default {
        data(){
                return {
                texts:'这是子组件的数据,将有子组件操作触发传给父组件'
                }
        },
        methods:{
            target:function(){ //有子组件的事件触发 自定义事件childevent
                this.$emit('childevent',this.texts);//触发一个在子组件中声明的事件 childEvnet
            }
        },
    }
    </script>
    
    • 父组件传递数据给子组件 (通过父组件操作子组件 ref的事件来触发)
    //父组件:parent.vue
    <template>
        <div>
            <child  v-on:childevent='wathChildEvent' ref="childcomp"></child>
            <input type="button" @click="parentEnvet" value="父组件触发" />
            <div>子组件的数据为:{{msg}}</div>
        </div>
    </template>
    <script>
    import child from "./child";
    export default {
        data(){
            return{
                msg:""
            }
        },
        components:{
            child
        },
        methods:{
            wathChildEvent:function(vals){//直接监听 又子组件触发的事件,参数为子组件的传来的数据
                console.log(vals);//这是子组件的数据,将有子组件操作触发传给父组件
                this.msg = vlas;
            },
            parentEnvet:function(){
                this.$refs['childcomp'].target(); //通过refs属性获取子组件实例,又父组件操作子组件的方法触发事件$meit
            }
        }
    }
    </script>
    
    //子组件:child.vue
    <template>
        <div>
          <!-- dothing..... -->
        </div>
    </template>
    <script>
    export default {
        data(){
                return {
                texts:'这是子组件的数据,将有子组件操作触发传给父组件'
                }
        },
        methods:{
            target:function(){ //又子组件的事件触发 自定义事件childevent
                this.$emit('childevent',this.texts);//触发一个在子组件中声明的事件 childEvnet
            }
        },
    }
    </script>
    

    兄弟组件间通信

    1.创建一个新Vue的实例,让各个兄弟共用同一个事件机制
    2.传递数据方:通过事件触发$emit(方法名,传递的数据)
    3.接收数据方:在mounted()钩子函数(挂载实例)中 触发事件$on(方法名,callback(接收数据的数据)),此时callback函数中的this已经发生了改变,可以使用箭头函数

    // 定义一个空的Vue实例,将通信事件挂载在该实例上
    // main.js
    import Vue from 'vue'
    import App from './App'
     
    export const eventBus = new Vue()
     
    new Vue({
        el: '#app',
        render: h => h(App)
    })
    
    • 兄弟组件A
    <template>
        <div class="message">
            <div class="message-header">
                <h5 v-text="theCardTitle"></h5>
            </div>
            <div class="message-body">
                <p class="message-text">我是Sister组件</p>
                <button @click="messageBrother" class="btn">给哥哥发消息</button>
     
                <div v-if="fromBrother" class="alert" v-html="fromBrother"></div>
            </div>
        </div>
    </template>
     
    <script>
        import { eventBus } from "../main";
     
        export default {
            name: "SisterCard",
            data: () => ({
                theCardTitle: "Sister Card",
                fromBrother: ""
            }),
            methods: {
                messageBrother() {
                    eventBus.$emit("sisterSaid", "妈妈说,该做作业了!(^_^)!!!");
                }
            },
            created() {
                eventBus.$on("brotherSaid", message => {
                    this.fromBrother = message;
                });
            }
        };
    </script>
    
    
    
    • 兄弟组件B
    <!-- BrotherCard.vue -->
    <template>
        <div class="message">
            <div class="message-header">
                <h5 v-text="theCardTitle"></h5>
            </div>
            <div class="message-body">
                <p class="message-text">我是Brother组件</p>
                <button @click="messageSister" class="btn">给妹妹发消息</button>
     
                <div v-if="fromSister" class="alert" v-html="fromSister"></div>
            </div>
        </div>
    </template>
     
    <script>
        import { eventBus } from "../main.js";
     
        export default {
            name: "BrotherCard",
            data: () => ({
                theCardTitle: "Brother Card",
                fromSister: ""
            }),
            methods: {
                messageSister() {
                    eventBus.$emit("brotherSaid", "妈妈说,该做作业了!(^_^)!!!");
                }
            },
            created() {
                eventBus.$on("sisterSaid", message => {
                    this.fromSister = message;
                });
            }
        };
    </script>
    
    • 父组件
    <!-- ParentCard -->
    <template>
        <div class="card">
            <div class="card-header">
                <h5 v-text="theCardTitle"></h5>
            </div>
            <div class="card-body">
                <brother-card></brother-card>
                <sister-card></sister-card>
            </div>
        </div>
    </template>
     
    <script>
        import BrotherCard from "./BrotherCard";
        import SisterCard from "./SisterCard";
     
        export default {
            name: "ParentCard",
            data: () => ({
                theCardTitle: "Parent Card"
            }),
            components: {
                BrotherCard,
                SisterCard
            }
        };
    </script>
    
  • 相关阅读:
    41:和为S的两个数
    40:数组中只出现一次的数字
    39-2:平衡二叉树
    39:二叉树的深度
    38:数字在排序数组中出现的次数
    37:两个链表的第一个公共结点
    36:数组中的逆序对
    35:第一个只出现一次的字符
    34:丑数
    33:把数组排成最小的数
  • 原文地址:https://www.cnblogs.com/KevinTseng/p/12979478.html
Copyright © 2011-2022 走看看