vue父子组件 子传父、父传子

子传父

  vue子传父使用$emit传值

  子组件:

<template>
    <div>
        <button @click="toParent">点击传到父级</button>
    </div>
</template>
<script>
export default {
    name: 'child',
    methods: {
        toParent () {
            this.$emit('fromChild', 'child')
        }
    }
}
</script>

  父组件:

<template>
    <div>
        <p>子级传过来的值:{{childVal}}</p>
        <child @fromChild="getChild"></child>
    </div>
</template>
<script>
import child from "@/components/child";
 
export default {
    name: 'parent',
    data () {
        return {
            childVal: ''
        }
    },
    components: {
        child
    },
    methods: {
        getChild (v) {
            this.childVal = v;
        }
    }
}
</script>

  

 

父传子

  子组件使用props接收 接收时还可以设置默认值 当没获取到值时 会使用设置的默认值

  父组件:

<template>
    <div>
        <child :tochild="parentVal"></child>
    </div>
</template>
<script>
import child from "@/components/child";
 
export default {
    name: 'parent',
    data () {
        return {
            parentVal: 'parent',
        }
    },
    components: {
        child
    }
}
</script>

  子组件:

<template>
    <div>
        <p>父级传过来的值:{{tochild}}</p>
    </div>
</template>
<script>
export default {
    name: 'child',
  //prop可以是数组也可以是对象
   props: ['
parentVal'],

   props: {
     tochild: String,
     default:'', //默认值
     required:true //是否为必填项
   }
}
</script>

 

转自 vue子传父、父传子 - loriby - 博客园 (cnblogs.com)

posted @ 2022-07-21 11:35  贾平凡  阅读(1537)  评论(0)    收藏  举报