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

父传子

父组件

 

<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>

也可以通过this.$parent.event来调用父组件方法

 

子传父

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

父组件

<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>

 

当和自定义组件和element-ui的组件嵌套使用时不生效,例如el-tags,因为嵌套使用两者就不是父子组件的关系

 

另外一种思路是通过v-slot作用域插槽获得子组件数据,然后通过触发事件获取

 

子传子

原理:通过eventBus将数据传递

bus.js

import Vue from 'vue'
export default new Vue({})

组件1

<template>
    <div>
        <p>son1Age: {{ son1Age }}</p>
        <button @click="sendData">CLICK</button>
    </div>
</template>
<script>
// 引入bus文件
import bus from './bus'
export default {
    data() {
        return {
            son1Age: 999
        }
    },
    methods: {
        sendData() {
            // 通过$emit方法调用bus上注册的getData事件,并将自身的数据作为参数传递过去
            bus.$emit('getData', this.son1Age)
        }
    },
}
</script>

组件2

<template>
    <div>
        <p>son2Age: {{ son2Age }}</p>
    </div>
</template>
<script>
// 引入bus文件
import bus from './bus'
export default {
    data() {
        return {
            son2Age: -999
        }
    },
    mounted() {
        // 在son2给envenBus注册事件,注意这里回调函数中的this指向该组件
        bus.$on('getData', (newAge) => {
            this.son2Age = newAge
        })
    }
}
</script>

 如果不想增加bus.js这个文件,可以在main.js里new一个vue对象并挂载到vue原型链上

import Vue from 'vue'

Vue.prototype.$bus = new Vue()
// 以后可以在子组件中直接使用this.$bus.$on注册和this.$bus.$emit调用

  

posted @ 2021-03-10 12:15  铽楉QAQ  阅读(829)  评论(0)    收藏  举报