vue组件传值的三种方式

父子组件传值:(二种传值:一个是props,一个是refs)

1:props

(1) 父组件给子组件传值:父组件绑定动态属性 传值 / 传方法 / 传实例

    <v-header
      :msg="msg"
      :fatherFunction="fatherFunction"  //父组件传递方法时不加()
      :home="this"
    ></v-header>

(2) 子组件通过props 接收父组件传过来的 值 / 方法 / 父亲实例

props: { msg: String, fatherFunction: Function, home: Object },
methods: {
    getparent() {
      console.log(this.home.msg); //获得父组件的内容
      this.home.fatherFunction("我是父组件的方法"); //执行父组件的方法
    },
    //执行父组件方法也可直接调用;<button @click="fatherFunction">执行</button>
 }
     特:如果子组件和父组件传值的props和data中定义的重复则会冲突,都有的时候会用props的!!

示例:在这里插入图片描述

2:refs

(1)父调用子组件的时候定义一个ref;

 <v-header
      :msg="msg"
      :fatherFunction="fatherFunction"
      :home="this"
      ref="header"
    ></v-header>

(2)父组件主动获取子组件的数据和方法

	1:调用子组件的时候定义一个ref;
    2:在父组件拿到子组件的内容/方法通过
     `this.$refs.header.属性  
      this.$refs.header.方法` 
 getSon() {
      console.log(this.$refs.header.sonMsg); //获得子组件的数据
      this.$refs.header.son(); //执行子组件的方法
 },
 fatherFunction(item) {
      console.log("父组件的方法", item);
 },

(3)子组件主动获取父组件的数据和方法

	1:调用子组件的时候定义一个ref;
    2:在子组件拿到父组件的内容/方法 
    `this.$parent.数据   
     this.$parent.方法`
 getFather() {
      console.log(this.$parent.msg);//获得父组件的数据
      this.$parent.fatherFunction("调用父组件的方法");//执行父组件的方法
 },
 son() {
      console.log("我是子组件的方法");
 },

示例:
在这里插入图片描述

非父子组件传值:(一种传值:$emit)

1:emit

(1):新建一个js文件,例:VueEvent.js 引入vue 实例化vue 暴露这个实例

import Vue from 'vue';
var VueEvent=new Vue();//新建这个实例
export default VueEvent;//暴露这个实例

(2):在需要广播的地方引入这个实例

import VueEvent from "../model/VueEvent.js";

(3):接收发送数据:

    发送: 通过VueEvent.$emit(名,数据)
  VueEvent.$emit("to-home", this.msg);
	接收: 通过VueEvent.$on(名,方法)
  VueEvent.$on("to-home", (data) => {
      console.log(data);
    });

示例:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值