美文网首页前端面试题
vue传值(Ⅰ)---父子组件传值

vue传值(Ⅰ)---父子组件传值

作者: 小薇同学v | 来源:发表于2020-06-10 10:57 被阅读0次

    vue父子组件传值

    父子组件传值 (Parent/Child)

    1、 props/$emit

    (1)父传子,props

    在父组件中引用的子组件上绑定

     <m-child :msg="'from Parent msg'"></m-child>

    在子组件中用props接收

      props: {

        msg: {

          type: String,

          default: ""

        }

      },

    (2)子传父,$emit

    在子组件中一般用事件触发,$emit中是传给父组件的自定义事件名和内容

     <button @click="walk">走妳</button>

     methods: {

        walk() {

            this.$emit('showMsg','from child')

        }

      }

    在父组件中引用的子组件上,通过监听子组件的自定义事件,获取传过来的内容,在data里定义展示传过来内容的变量,并写一个方法接收这个传过来的值

      <m-child :msg="'from Parent msg'" @showMsg="show"></m-child>

     data() {

        return {

          msgOne: ""

        };

      },

      methods: {

        show(val) {

          this.msgOne = val;

        }

      }

    2、$parent/$children

    在父组件中可以用this.$children接收子组件传过来的data里的变量值,或者定义的方法

    在子组件中可以用this,$parent接收父组件传过来的data里的变量值,或者定义的方法

     mounted() {

        console.log(this.$parent);

      }

    3、ref

    本质上与$parent/$children是一样的,但是使用的操作有所不同,在组件上绑定ref,接收的时候需要this.$refs

     <m-child :msg="'from Parent msg'" @showMsg="show" ref="child"></m-child>

    mounted () {      console.log(this.$children[0].child);      console.log('ref',this.$refs.child);  }

    相关文章

      网友评论

        本文标题:vue传值(Ⅰ)---父子组件传值

        本文链接:https://www.haomeiwen.com/subject/ovuutktx.html