vue2父子组件传参方式汇总

一、props和$emit函数

父子通信:

父传子:通过props的方式来传递数据

子传父:通过自定义的事件来进行触发传递

将这种参数传递的方式称为 自定义事件的方式通信。而且也是目前工作中用的最多的。

父组件代码eg:

<template>
  <div>
    <h2>父组件数据</h2>
    <p>{
   
   {username}}</p>
    <ChildrenCompVue :username="username" @mychange="changeUsername"></ChildrenCompVue>
  </div>
</template>
<script>
import ChildrenCompVue from './ChildrenComp.vue'
export default {
    data(){
        return{
            username:"xiaowang"
        }
    },
    components:{
        ChildrenCompVue
    },
    methods:{
        changeUsername(val){
            this.username = val
        }
    }
}
</script>
<style>
</style>
@mychange="changeUsername"

中,mychange就是你们自己定义的事件名字。这个事件名字不要跟系统名字一样,比如:click、change、focus等等 

子组件代码eg:

(子组件触发自定义事件,触发自定义对应事件函数就会立即执行)

<template>
  <div>
    <h2>子组件</h2>
    <p>外部数据:{
   
   {username}}</p>
    <button @click="updateUser">修改username</button>
  </div>
</template>
<script>
export default {
    // 无需再props接受外部的回调
    props:["username"],
    methods:{
        updateUser(){
            // 触发自定义事件
            this.$emit("mychange","xiaofeifei")
        }
    }
}
</script>
<style>
</style>

$emit是vue提供给我们的一个api,可以触发自定义事件

优点:子组件通过api触发事件就可以传递参数,无需自己调用函数

缺点:额外新增事件需要自己维护

 二、$parent和$children

this代表的当前这个组件,每个组件上面都有$parent 属性代表得到父组件。$children代表所有的子组件。

我们可以再父组件中$children获取所有子组件调用他的属性和方法

我们也可以在子组件中$parent获取到唯一的父组件,调用属性和方法

父组件代码eg:

<template>
    <div>
        <ChildrenCompVue :username="username"></ChildrenCompVue>
        <button @click="showMessage">获取到子组件的数据</button>
    </div>
</template>
<script>
import ChildrenCompVue from './ChildrenComp.vue'
export default {
    data() {
        return {
            username: "xiaowang",
        }
    },
    components: {
        ChildrenCompVue
    },
    methods: {
        showMessage(){
            console.log(this.$children[0].password);
            this.$children[0].show()
        }
    }
}
</script>
<style>
</style>

子组件代码eg:

<template>
    <div>
        <h2>子组件</h2>
        <p>外部数据:{
   
   { username }}</p>
        <button @click="parentMethods">通过$parent调用父组件</button>
    </div>
</template>
<script>
export default {
    // 无需再props接受外部的回调
    props: ["username"],
    data() {
        return {
            password: "123"
        }
    },
    methods: {
        show(){
            console.log(123345);
        },
        parentMethods(){
            console.log(this.$parent.changeUsername("王二麻子"));
        }
    }
}
</script>
<style>
</style>

$parent调用父组件的方法

优点:通信方便,任何一个地方得到对象就可以操作

缺点:组件嵌套比较多的情况下,这种操作并不方便

三、$attrs和$listeners

this对象上面有一个$attrs属性。接受外部数据,但是排除props接受过后的数据。

外部数据进入子组件分成两部分:props接受。$attrs来接受

外部数据传到子组件的时候,如果数据在$attrs里,你们可以直接使用

<template>
<p>{
   
   {$attrs.age}}</p>
</template>

子组件要触发父组件自定义事件,我们可以$listeners获取到所有的自定义事件

<button @click="$listeners.changeMyUser">自己触发$listeners</button>

可以直接调用事件,触发这个事件,但是一般来说不推荐使用 

猜你喜欢

转载自blog.csdn.net/wzy_PROTEIN/article/details/130970957