Vue组件之间传值/调用几种方式

2022-12-02 15:09:15

目录组件之间传值/调用方法的几种方式(一)父组件向子组件传值==props(二)子组件向父组件传值==$emit,也可以用来调用父组件中的方法(三)可以通过parent和parent和...

目录
组件之间传值/调用方法的几种方式
(一)父组件向子组件传值==props
(二)子组件向父组件传值==$emit,也可以用来调用父组件中的方法
(三)可以通过 p a r e n t 和 parent和 parent和children获取父子组件参数
(四)兄弟之间传值===vuex
(五)父组件调用子组件的方法===ref
推荐

组件之间传值/调用方法的几种方式

(一)父组件向子组件传值==props

1.在父组件中使用子组件的地方绑定数据

<children :message="message"></children>

2.子组件使用props接收父组件传过来的数据

props:{
     message:String
}

3.示例:

Vue组件之间传值/调用几种方式

(二)子组件向父组件传值==$emit编程,也可以用来调用父组件中的方法

1.子组件直接使用$emit将内部数据传递给父组件

this.$emit("childByValue",this.childValue);

2.父组件中接收数据

<template>
     <child @childByVlaue="childByVlaue"></dhild>
</template>
methods:{
     childByValue:function(childValue){
          this.name=childValue;
     }
}

(三)可以通过 p a r e n t 和 parent和 parent和children获取父子组件参数

$children[i].params

this.$parent.params

(四)兄弟之间传值===Vuex

1.在state里编程定义数据和属性

state: {
    userName: '',
  },

2.在mutation里定义函数

mutations: {
    setUserName(state, name) {
      state.userName = name
    },
},

3.设置值

this.$store.comit('setUserName',params)

4.获取值

this.$store.state.user.userName

(五)父组件调用子组件的方法===ref

1.子组件的方法

methods:{
     childMethod(){
          alert("我是子组件的方法");
     }
}

2.父组件调用子组件的方法

<template>
     <child ref="child"></child>
     <div @click="parentMethod"></div>
</template>
methods:{
     parentMethod(){
          this.$refs.child.childMethod();
     }
} 

推荐

vue 组件间的通信之子组件向父组件传值的方式

详解Vue3 父组件调用子组件方法($refs 在setup()、<script setup> 中使用)

到此这篇关于Vue组件之间传值/调用方法的几种方式的文章就介绍到这了,更多相关vue组件传值内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!