首页 > 其他 > 详细

Vue数据 父传子 子传父 子传子

时间:2021-03-10 15:20:19      阅读:29      评论:0      收藏:0      [点我收藏+]

父传子

父组件

 

<template>
    <div>
        <!--  通过给子组件自定义属性和事件来传递数据 -->
        <son :fatherAge="age" @fatherMethod="log"></son>
        
    </div>
</template>
<script>
import son from ./son.vue
export default {
    name: father,
    data() {
        return {
            age: 999
        }
    },
    methods: {
        log() {
            console.log(1)
        }
    },
    components: {
        son
    }
}
</script>

 

 

 

 

子组件

<template>
    <div>
        <!-- 使用父组件传递的数据或方法时,用的是自定义的属性名,建议使用与变量相同的名称,方便使用 -->
        <p>{{ fatherAge }}</p>
        <button @click="useFatherMethod">CLICK</button>
    </div>
</template>
<script>
export default {
    // props设置获取哪些父组件传递的变量,Number指获取的变量必须为数字型,否则报错
    props: {
        fatherAge: Number
    },
    methods: {
        // 方法不需要设置props,直接使用$emit方法调用父组件方法
        useFatherMethod() {
            this.$emit(fatherMethod)
        }
    },
}
</script>

子传父

子组件利用父组件方法,将参数传递

父组件

<template>
    <div>
     <!-- 类似vuex,利用自身方法修改自身的数据,以达到传递数据的目的 --> <p>father: {{ fatherAge }}</p> <son @fatherMethod="changeAge"></son> </div> </template> <script> import son from ./son.vue export default { name: father, data() { return { fatherAge: 999 } }, methods: { changeAge(sonAge) { this.fatherAge = sonAge } }, components: { son } } </script>

子组件

<template>
    <div>
        <p>sonAge: {{ sonAge }}</p>
        <button @click="useFatherMethod">CLICK</button>
    </div>
</template>
<script>
export default {
    data() {
        return {
            sonAge: -999
        }
    },
    methods: {
        // 调用父组件方法时,第一个参数是监听的事件名,后面的是事件方法的参数
        useFatherMethod() {
            this.$emit(fatherMethod, this.sonAge)
        }
    },
}
</script>

子传子

晚点写

 

Vue数据 父传子 子传父 子传子

原文:https://www.cnblogs.com/xijiang/p/14510815.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!