zoukankan      html  css  js  c++  java
  • vue传值总结

    一、父组件 向 子组件传值

    1、父组件调用子组件的时候,在子组件身上绑定动态属性
    <template>
        <div>
            <Child :title="title"> </Child>//子组件
        </div>
    </template>
    
    2、在对应的子组件中,通过props属性接收传递过来的值
    props:{
            title:{
                type:String,
                default:'我是标题'
            }
    }
    
    3、在子组件中使用该值
    <div>{{title}}</div>
    
    总结:props传递数据原则:单向数据流。不推荐子组件直接操作父组件传递过来的数据。

    二、子组件 向 父组件中传值

    1、子组件 通过自定义事件向父组件传递信息
    //子组件 Child.vue
    <button @click="changeLarge">扩大父组件的字号</button> 
    
    methods:{
            changeLarge(){
                this.$emit('enlargetxt',5)   //enlargetxt 是自定义事件名称,5是传递的参数。用$event接收,如下图。
            }
    }
    
    2、父组件 监听子组件的事件 // 子组件 调用 父组件的方法
    <template>
        <div class="parent">
            <Child  @enlargetxt="handle($event)"/>  //@ 后面是自定义事件名称,$event 是实参,对应于上面传来的 5
            <p  :style="{fontSize:fontSize+'px'}">132456789</p>
        </div>
    </template>
    
    methods:{
           
            handle($event){  //$event此处是形参,可用任意参数
                  this.fontSize+=$event;
            }
        }
    

    三、兄弟组件通信

    1.定义一个公共文件 eventBus.js
    import Vue from 'vue'
    export default new Vue()
    
    2.在需要通信的同级组件中分别引入eventBus.js文件
    import eventBus from '../eventBus.js'
    
    3.发出数据的组件 Son1.vue
    <button @click="emitSon2">发出数据</button>
    
    //方法
    methods:{
        emitSon2(){
            eventBus.$emit('toSon2',this.name)
        }
    }
    
    
    4.接收数据的组件 son2.vue
    mounted:{
        eventBus.$on("toSon2", (data) => {
              console.log(data)
        });
    }
    
    总结:1、触发事件 eventBus.$emit('todo',this.name) 2、监听事件 eventBus.$on('todo',function(data){ }) 3、如果有需要,还可以销毁事件eventBus.$off('todo')



    主动获取数据部分

    一、父组件 主动获取 子组件的数据和方法

    1、父组件调用子组件的时候,在子组件身上定义ref
    <template>
        <div>
            <Child ref="childId"> </Child>//子组件
            //注:ref相当于dom里的id,在js里边调用方式是:this.$refs.childId
        </div>
    </template>
    
    2、在父组件调用子组件的数据和方法
    this.$refs.childId.数据或方法
    

    二、子组件 主动获取 父组件的数据和方法

    在子组件里边
    this.$parent.数据或者方法
    
  • 相关阅读:
    OSX: 私人定制Dock默认程序图标
    PHP+MYSQL分页原理
    Python 数据结构与算法 —— 哈弗曼树
    C#制作文本转换为声音的demo,保存音频文件到本地
    时区与时间(二)
    时区与时间(二)
    摄影的艺术
    摄影的艺术
    名词、文化概念的解释
    名词、文化概念的解释
  • 原文地址:https://www.cnblogs.com/maizilili/p/12402125.html
Copyright © 2011-2022 走看看