Vue 子组件掉用父组件方法和父组件掉用子组件的方法

一、父组件触发子组件的方法

      1、在子组件上添加一个 ref 的标识

 <son-component ref="mySonComp" @fatherMenthod="fatherMenthod"></son-component>

      2、然后通过 this.$refs['mySonComp'] 加上方法名来调用就可以了

this.$refs['mySonComp'].sonMenthod()

      其中,sonMenthod为定义在子组件methods里的一个function,即子组件定义的方法。

二、子组件触发父组件的方法

      1、如上面第一步代码所示,通过@在子组件上绑定一个自定义事件,前者为需要在子组件触发的方法名,后者为要触发的父组件里的方法。
      2、在子组件中通过 this.$emit 来触发定义的方法名就可以了

this.$emit('fatherMentod')

      3、关于子组件向父组件传值

      在 this.$emit 多增加一个参数即可,例如

this.$emit('fatherMethod', 'This is son param')

      只要记住 $ref $emit 这两个关键字,然后记住写法就很简单

三、父组件向子组件传递值

      1、需要传递给子组件的值定义在父组件中,本案例传递一个字符串和数组,如下

data() {
    return {
        paramArr: [
            {id: 1, name: 'test1'},
            {id: 2, name: 'test2'}
        ],
        paramStr: 'This is string'
    }
}

      2、在父组件中调用、注册并引用子组件

      调用

import sonComponent from './son-component'

      注册

components: {
    sonComponent
}

      引用

 <son-component :paramArr="paramArr" :paramStr="paramStr"></son-component>

      使用 v-bind 的的方式传递值,v-bind 是可以省略的,直接用 : 代替

      3、子组件使用 props 接收父组件传递的值

props: {
    paramArr: {
        type: Array,
        required: true
    },
    paramStr: {
        type: String,
        required: true
    }
}

      4、子组件使用父组件的值

<!-- 使用字符串 -->
<span v-text="paramStr" />
<!-- 使用数组 -->
<span v-for="item in paramArr" :key="item.id">
    <strong>ID:</strong><span>{{item.id}}</span>
    <br />
    <strong>Name:</strong><span>{{item.name}}</span>
</span>

      注意:子组件接收父组件的值分为:引用类型和普通类型

  • 普通类型:字符串(String)、数字(Number)、布尔值(Boolean)、空(Null)
  • 引用类型:数组(Array)、对象(Object)

      其中,普通类型是可以在子组件中更改,不会影响其他兄弟子组件内同样调用的来自父组件的值,但是,引用类型的值,当在子组件中修改后,父组件的也会修改,那么后果就是,其他同样引用了改值的子组件内部的值也会跟着被修改。除非你有特殊的要求这么去做,否则最好不要这么做。

发布了68 篇原创文章 · 获赞 48 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Wjhsmart/article/details/87269135