Vue组件传值的若干种方式

01 父传子

propsprops可以是数组或对象,用于接收来自父组件通过v-bind传递的数据。当props为数组时,直接接收父组件传递的属性;当 props 为对象时,可以通过type、default、required、validator等配置来设置属性的类型、默认值、是否必传和校验规则。

app.vue

<template>
    <div id="app">
        Hello
        <!-- 想改变传递过去的数据,直接在自己的组件里面修改 -->
        <button @click="msg = 'xxx'">修改</button>
        <hr />
        <child :msg="msg" />
    </div>
</template>

<script>
import Child from '@/Child'
export default {
    name: 'App',
    data() {
        return {
            msg: 'Hello World',
        }
    },
    components: {
        Child,
    },
}
</script>

Child.vue  

<template>
    <div>Child: {{ msg }}</div>
</template>

<script>
export default {
    name: 'Child',
    props: {
        msg: {
            type: String,
        },
    },
}
</script>

02 子传父 

$emit在父子组件通信时,使用$emit来触发父组件v-on在子组件上绑定相应事件的监听。

App.vue

<template>
    <div id="app">
        {{ msg }}
        <hr />
        <child @changeMsg="changeMsg" />
    </div>
</template>

<script>
import Child from '@/components/Child'
export default {
    name: 'App',
    data() {
        return {
            msg: '父亲的 Hello World',
        }
    },
    components: {
        Child,
    },
    methods: {
        changeMsg(childData) {
            this.msg = childData
        },
    },
}
</script>

Child.vue  

<template>
    <div>
        Child
        <button @click="handleChangeMsg">修改父亲的数据</button>
    </div>
</template>

<script>
export default {
    name: 'Child',
    methods: {
        handleChangeMsg() {
            this.$emit('changeMsg', '~~~~~~')
        },
    },
}
</script>

03 兄弟传值(状态提升)

所谓状态提升,就是把需要操作的数据放到统一的父级里面,一个子组件修改父组件的数据,父组件的数据再传递给另一个子组件

需求:Child1.vue 中修改 Child2.vue 中的数据

App.vue

<template>
    <div id="app">
        App
        <hr />
        <child1 @changeData="changeData" />
        <child2 :msg="msg" />
    </div>
</template>

<script>
import Child1 from '@/components/Child1'
import Child2 from '@/components/Child2'
export default {
    name: 'App',
    data() {
        return {
            msg: 'Hello World',
        }
    },
    components: {
        Child1,
        Child2,
    },
    methods: {
        changeData(childData) {
            // 直接修改自己的数据,另一个儿子中的数据自然就变了
            this.msg = childData
        },
    },
}
</script>

Child1.vue

<template>
    <div>
        Child1
        <button @click="handleClick">修改 Child2 的数据</button>
    </div>
</template>

<script>
// 想在 Child1 里面修改 Child2 里面的数据
export default {
    name: 'Child1',
    methods: {
        handleClick() {
            this.$emit('changeData', '~~~~')
        },
    },
}
</script>

Child2.vue  

<template>
    <div>Child2: {{ msg }}</div>
</template>

<script>
export default {
    name: 'Child2',
    props: ['msg'],
    data() {
        return {}
    },
    methods: {},
}
</script>

04 兄弟通信(EventBus)

eventBus又称事件总线,通过注册一个新的Vue实例,通过调用这个实例的$emit和$on等来监听和触发这个实例的事件,通过传入参数从而实现组件的全局通信。

main.js

import Vue from 'vue'
import App from './App.vue'

// !#1 事件总线
Vue.prototype.$hub = new Vue()

Vue.config.productionTip = false

new Vue({
    render: (h) => h(App),
}).$mount('#app')

App.vue

<template>
    <div id="app">
        App
        <hr />
        <child1 />
        <child2 />
    </div>
</template>

<script>
import Child1 from '@/components/Child1'
import Child2 from '@/components/Child2'

export default {
    name: 'App',
    components: {
        Child1,
        Child2,
    },
}
</script>

Child1.vue  

<template>
    <div>
        Child1
        <button @click="handleClick">改变Child2中的数据</button>
    </div>
</template>

<script>
export default {
    name: 'Child1',
    methods: {
        handleClick() {
            // !#2
            this.$hub.$emit('changeData', '~~~~')
        },
    },
}
</script>

Child2.vue  

<template>
    <div>Child2: {{ msg }}</div>
</template>

<script>
export default {
    name: 'Child2',
    data() {
        return {
            msg: 'Hello World',
        }
    },
    mounted() {
        // !#3 准备一个事件监听
        this.$hub.$on('changeData', (child1Data) => {
            this.msg = child1Data
        })
    },
}
</script>

 注意:Vue3 当中废弃了这种写法

05 Vuex

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        username: 'Tom',
    },
    mutations: {
        changeUserName(state, uname) {
            state.username = uname
        },
    },
})

Child1.vue  

<template>
    <div>
        Child1
        <button @click="handleChange">change</button>
    </div>
</template>

<script>
export default {
    name: 'Child1',
    methods: {
        handleChange() {
            this.$store.commit('changeUserName', '~~~~~')
        },
    },
}
</script>

Child2.vue  

<template>
    <div>Child2: {{ username }}</div>
</template>

<script>
import { mapState } from 'vuex'
export default {
    name: 'Child2',
    computed: {
        ...mapState(['username']),
    },
}
</script>

06 Refs

$refs在实现组件通信上,可以将 $refs 绑定在子组件上,从而获取子组件实例。

App.vue

<template>
    <div id="app">
        App
        <button @click="handleClick">change</button>
        <hr />
        <child ref="c" />
    </div>
</template>

<script>
// 需求:父改子的数据
import Child from './components/Child.vue'

export default {
    name: 'App',
    components: {
        Child,
    },
    methods: {
        handleClick() {
            // 操作数据
            // this.$refs.c.msg = '~~~~~~';
            this.$refs.c.changeData()
        },
    },
}
</script>

 Child.vue

<template>
    <div>Child: {{ msg }}</div>
</template>

<script>
export default {
    name: 'Child',

    data() {
        return {
            msg: 'Hello World',
        }
    },

    methods: {
        changeData() {
            this.msg = '~~~~~'
        },
    },
}
</script>

07 $parent / $children(父改子,子改父)

$parent可以在 Vue 中直接通过this.$parent来获取当前组件的父组件实例(如果有的话)。

$children也可以在 Vue 中直接通过this.$children来获取当前组件的子组件实例的数组。但是需要注意的是,this.$children数组中的元素下标并不一定对用父组件引用的子组件的顺序,例如有异步加载的子组件,可能影响其在 children 数组中的顺序。所以使用时需要根据一定的条件例如子组件的name去找到相应的子组件。

App.vue

<template>
    <div id="app">
        {{ msg }}
        <button @click="handleClick">change</button>
        <hr />
        <child ref="c" />
    </div>
</template>

<script>
// 需求:父改子的数据
import Child from './components/Child.vue'

export default {
    name: 'App',
    components: {
        Child,
    },
    data() {
        return {
            msg: 'H',
        }
    },
    methods: {
        handleClick() {
            // 操作数据
            // this.$refs.c.msg = '~~~~~~';
            // this.$refs.c.changeData();
            // console.log(this.$children[0] === this.$refs.c); // true
            this.$children[0].changeData()
        },
    },
}
</script>

Child.vue  

<template>
    <div>
        Child: {{ msg }}
        <button @click="handleClick">子改父</button>
    </div>
</template>

<script>
export default {
    name: 'Child',

    data() {
        return {
            msg: 'Hello World',
        }
    },

    methods: {
        changeData() {
            this.msg = '~~~~~'
        },
        handleClick() {
            // 可以拿到父亲的数据,就可以拿到父亲的方法,不再演示了
            this.$parent.msg = '~~~~~~~~~~~~'
        },
    },
}
</script>

08 provide / inject(跨层级通信 )

provide是一个对象,或者是一个返回对象的函数。该对象包含可注入其子孙的 property ,即要传递给子孙的属性和属性值。

injcet一个字符串数组,或者是一个对象。当其为字符串数组时,使用方式和props十分相似,只不过接收的属性由data变成了provide中的属性。当其为对象时,也和props类似,可以通过配置default和from等属性来设置默认值,在子组件中使用新的命名属性等。

App.vue

<template>
    <div id="app">
        App
        <button @click="handleClick">改数据</button>
        <hr />
        <child1 />
    </div>
</template>

<script>
import Child1 from './components/Child1.vue'

export default {
    name: 'App',
    data() {
        return {
            username: 'ifer',
            info: {
                age: 18,
            },
        }
    },
    components: {
        Child1,
    },
    // 不能访问 data 中的数据
    /* provide: {
        username: 'ifer',
    } */
    // 不是响应式的
    /* provide() {
        return {
            username: this.username,
        }
    } */
    // 传入对象是响应式的
    provide() {
        return {
            info: this.info,
        }
    },
    methods: {
        handleClick() {
            this.info.age = '~~~~~~'
        },
    },
}
</script>

Child3.vue  

<template>
    <div>
        <p>Child3: {{ info.age }}</p>
    </div>
</template>

<script>
export default {
    name: 'Child3',
    inject: ['info'],
}
</script>

09 $attrs

$attrs用来接收父作用域中不作为 prop 被识别的 attribute 属性,并且可以通过v-bind="$attrs"传入内部组件——在创建高级别的组件时非常有用。

App.vue

<template>
    <div id="app">
        App
        <button @click="changeData">改变数据</button>
        <hr />
        <child1 class="box" :username="username" :age="age" />
    </div>
</template>

<script>
import Child1 from './components/Child1.vue'

export default {
    name: 'App',
    data() {
        return {
            username: 'ifer',
            age: 18,
        }
    },
    components: {
        Child1,
    },
    methods: {
        changeData() {
            this.username = '~~~~~~~~'
            this.age = '188888888'
        },
    },
}
</script>

Child1.vue  

<template>
    <div class="child1">
        Child1{{ $attrs }}
        <hr />
        <child2 v-bind="$attrs" />
    </div>
</template>

<script>
import Child2 from './Child2'
export default {
    name: 'Child1',
    components: {
        Child2,
    },
    props: ['username'],
    // !非 Props 属性默认会作用于组件的根节点,但 class、style 除外
    inheritAttrs: false,
}
</script>

Child2.vue  

<template>
    <div class="child2">Child2: {{ $attrs }}</div>
</template>

<script>
export default {
    name: 'Child2',
}
</script>

 10  $listeners

$listeners包含了父作用域中的 v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件

App.vue

<template>
    <div id="app">
        {{ msg }}
        <hr />
        <child1 @test1="test1" @test2="test2" />
    </div>
</template>

<script>
import Child1 from './components/Child1.vue'

export default {
    name: 'App',
    data() {
        return {
            msg: 'H',
        }
    },
    components: {
        Child1,
    },
    methods: {
        test1(msg) {
            this.msg = msg
        },
        test2() {
            console.log('test2')
        },
    },
}
</script>

Child1.vue  

<template>
    <div>
        Child1
        <hr />
        <child2 v-on="$listeners" />
    </div>
</template>

<script>
import Child2 from './Child2'
export default {
    name: 'Child1',
    components: {
        Child2,
    },
}
</script>

Child2.vue

<template>
    <div>
        Child2
        <button @click="handleClick">改变爷爷的数据</button>
    </div>
</template>

<script>
export default {
    name: 'Child2',
    methods: {
        handleClick() {
            // 第一种触发的方式
            // this.$listeners.test1('~~~~~~~~')
            // 第二种触发的方式
            this.$emit('test1', '~~~~~~~~')
        },
    },
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值