Vue2组件间常用传值方式

本文详细介绍了Vue中组件间通信的不同方式,包括props、v-model、sync、$ref、事件总线(EventBus)、Vuex状态管理以及插槽的使用。重点讲解了父子、兄弟组件和跨层级通信的最佳实践。

组件的常用传值方式

  1. props
  2. vue自定义事件
  3. 全局事件总线
  4. v-model
  5. sync
  6. attrs与attrs与attrslisteners
  7. $ref & $children & $parent
  8. provide与inject
  9. Vuex
  10. 插槽 ==> 作用域插槽

根据通信的2个组件间的关系来选择一种通信方式

  父子
		props
		vue自定义事件
		v-model
		.sync
		$ref, $children与$parent
		插槽 ==> 作用域插槽
	祖孙
		$attrs与$listeners
		provide与inject
	兄弟或其它/任意
		全局事件总线
		Vuex

- 方式一: props

父组件向子组件传送数据

 子组件接收到数据之后,不能直接修改父组件的数据。会报错,所以当父组件重新渲染时,数据会被覆盖。如果子组件内要修改的话推荐使用
   computed
// Parent.vue 传送
<template>
    <child :msg="msg"></child>
</template>

// Child.vue 接收
export default {
  // 写法一 用数组接收
  props:['msg'],
  // 写法二 用对象接收,可以限定接收的数据类型、设置默认值、验证等
  props:{
      msg:{
          type:String,
          default:'这是默认数据'
      }
  },
  mounted(){
      console.log(this.msg)
  },
}

- 方式二:.sync

 可以帮我们实现父组件向子组件传递的数据 的双向绑定,所以子组件接收到数据后可以直接修改,并且会同时修改父组件的数据
// Parent.vue
<template>
    <child :page.sync="page"></child>
</template>
<script>
export default {
    data(){
        return {
            page:1
        }
    }
}

// Child.vue
export default {
    props:["page"],
    computed(){
        // 当我们在子组件里修改 currentPage 时,父组件的 page 也会随之改变
        currentPage {
            get(){
                return this.page
            },
            set(newVal){
                this.$emit("update:page", newVal)
            }
        }
    }
}
</script>

- 方式三 v-model

 实现将父组件传给子组件的数据为双向绑定,子组件通过 $emit 修改父组件的数据
// Parent.vue
<template>
    <child v-model="value"></child>
</template>
<script>
export default {
    data(){
        return {
            value:1
        }
    }
}

// Child.vue
<template>
    <input :value="value" @input="handlerChange">
</template>
export default {
    props:["value"],
    // 可以修改事件名,默认为 input
    model:{
        // prop:'value', // 上面传的是value这里可以不写,如果属性名不是value就要写
        event:"updateValue"
    },
    methods:{
        handlerChange(e){
            this.$emit("input", e.target.value)
            // 如果有上面的重命名就是这样
            this.$emit("updateValue", e.target.value)
        }
    }
}
</script>


- 方式四 ref

 注意:ref 如果在普通的DOM元素上,引用指向的就是该DOM元素;如果在子组件上,引用的指向就是子组件实例,然后父组件就可以通过 ref 主动获取子组件的属性或者调用子组件的方法
// Child.vue
export default {
    data(){
        return {
            name:"天天"
        }
    },
    methods:{
        someMethod(msg){
            console.log(msg)
        }
    }
}

// Parent.vue
<template>
    <child ref="child"></child>
</template>
<script>
export default {
    mounted(){
        const child = this.$refs.child
        console.log(child.name) // 天天
        child.someMethod("调用了子组件的方法")
    }
}
</script>

- 方式五 : $emit / v-on (子传父)

// Child.vue 派发
export default {
  data(){
      return { msg: "这是发给父组件的信息" }
  },
  methods: {
      handleClick(){
          this.$emit("sendMsg",this.msg)
      }
  },
}
// Parent.vue 响应
<template>
    <child v-on:sendMsg="getChildMsg"></child>
    // 或 简写
    <child @sendMsg="getChildMsg"></child>
</template>

export default {
    methods:{
        getChildMsg(msg){
            console.log(msg) // 这是父组件接收到的消息
        }
    }
}

- 方式六 EventBus

 - EventBus 是中央事件总线,不管是父子组件,兄弟组件,跨层级组件等都可以使用它完成通信操作
// 方法一
// 抽离成一个单独的 js 文件 Bus.js ,然后在需要的地方引入
// Bus.js
import Vue from "vue"
export default new Vue()

// 方法二 直接挂载到全局
// main.js
import Vue from "vue"
Vue.prototype.$bus = new Vue()

// 方法三 注入到 Vue 根对象上
// main.js
import Vue from "vue"
new Vue({
    el:"#app",
    data:{
        Bus: new Vue()
    }
})

以方法一为例,使用如下

// 在需要向外部发送自定义事件的组件内
<template>
    <button @click="handlerClick">按钮</button>
</template>
import Bus from "./Bus.js"
export default{
    methods:{
        handlerClick(){
            // 自定义事件名 sendMsg
            Bus.$emit("sendMsg", "这是要向外部发送的数据")
        }
    }
}

// 在需要接收外部事件的组件内
import Bus from "./Bus.js"
export default{
    mounted(){
        // 监听事件的触发
        Bus.$on("sendMsg", data => {
            console.log("这是接收到的数据:", data)
        })
    },
    beforeDestroy(){
        // 取消监听
        Bus.$off("sendMsg")
    }
}

- 方法七 Vuex

 - Vuex 是状态管理器,集中式存储管理所有组件的状态。这一块内容过长,如果基础不熟的话可以看这个[Vuex](https://vuex.vuejs.org/zh/guide/),然后大致用法如下

store中的index.js

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
import state from './state'
import user from './modules/user'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    user
  },
  getters,
  actions,
  mutations,
  state
})
export default store

然后再main里面引入

import Vue from "vue"
import store from "./store"
new Vue({
    el:"#app",
    store,
    render: h => h(App)
})

在组件中使用

import { mapGetters, mapMutations } from "vuex"
export default{
    computed:{
        // 方式一 然后通过 this.属性名就可以用了
        ...mapGetters(["引入getters.js里属性1","属性2"])
        // 方式二
        ...mapGetters("user", ["user模块里的属性1","属性2"])
    },
    methods:{
        // 方式一 然后通过 this.属性名就可以用了
        ...mapMutations(["引入mutations.js里的方法1","方法2"])
        // 方式二
        ...mapMutations("user",["引入user模块里的方法1","方法2"])
    }
}

// 或者也可以这样获取
this.$store.state.xxx
this.$store.state.user.xxx

- 方式八 插槽 slot

 插槽就是子组件中的提供给父组件使用的一个占位符,用 表示,父组件可以在这个占位符中填充任何模板代码,如
   HTML、组件等,填充的内容会替换子组件的标签。插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制
1. 默认插槽
//父组件
<template>
    <son :title="电影">
        <ul>
            <li v-for="(item,index) in films" :key="index">{{ item }}</li>
        </ul>
    </son>
</template>

<script>
    export default{
        name:'fath',
        components:{ son },
        data:{
            return {
                films:['猫和老鼠','哆唻A梦','樱桃小丸子']
            }
        }
    }
</script>

子组件

<template>
    <div>
        <h3>{{ title }}</h3>
        <!-- 定义一个插槽(设置一个位置,等着组件的使用者进行填充) -->
        <slot>这是一个插槽,当使用插槽时,此文字不展示被填充内容覆盖</slot>
    </div>
</template>

<script>
    export default{
        name:'son',
        props:['listData','title']
    }
</script>

注意:
1 父级的填充内容如果指定到子组件的没有对应名字插槽,那么该内容不会被填充到默认插槽中。即具名插槽用name属性来表示插槽的名字,不传为默认插槽
2. 如果子组件没有默认插槽,而父级的填充内容指定到默认插槽中,那么该内容就不会填充到子组件的任何一个插槽中
3. 如果子组件有多个默认插槽,而父组件所有指定到默认插槽的填充内容,将会且全都填充到子组件的每个默认插槽中

2. 具名插槽
具名插槽其实就是给插槽娶个名字。一个子组件可以放多个插槽,而且可以放在不同的地方,而父组件填充内容时,可以根据这个名字把内容填充到对应插槽中
//父组件
<div>
    <son>
        <div v-slot:content>
            <span>{{ 给内容区放点东西 }}</span>
        </div>
        <!-- vue 2.6版本后语法,在template中可以直接写v-slot:slot1 -->
        <template slot="footer">
            <div> 
                <span>{{ 给底部放点东西 }}</span>
            </div>
        </template>
    </son>
</div>

子组件

<template>
    <h2>{{ 这里是头部 }}</h2>
    <slot name='content'>这里是内容插槽,当使用插槽时,此文字不展示被填充内容覆盖</div>
    <slot name='footer'>这里是底部插槽,当使用者没有传递具体结构时,此文字会显示</div>
</template>

作用域插槽
 作用域插槽其实就是带数据的插槽,即带参数的插槽,简单的来说就是子组件提供给父组件的参数,该参数仅限于插槽中使用,父组件可根据子组件传过来的插槽数据来进行不同的方式展现和填充插槽内容。

子组件

<template>
  <div class="child">

    <h3>这里是子组件</h3>
    <slot  :data="data"></slot>
  </div>
</template>

 export default {
    data: function(){
      return {
        data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
      }
    }
}

父子间

<template>
  <div class="father">
    <h3>这里是父组件</h3>
    <!--第一次使用:用flex展示数据:  class="tmpl"-->
    <child>
      <template slot-scope="user">
        <div class="tmpl">
          <span v-for="item in user.data">{{item}}</span>
        </div>
      </template>

    </child>

    <!--第二次使用:用列表展示数据-->
    <child>
      <template slot-scope="user">
        <ul>
          <li v-for="item in user.data">{{item}}</li>
        </ul>
      </template>

    </child>

    <!--第三次使用:直接显示数据-->
    <child>
      <template slot-scope="user">
       {{user.data}}
      </template>

    </child>

    <!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽-->
    <child>
      我就是模板
    </child>
  </div>
</template>

所以slot的用法可以分为三类,分别是默认插槽、具名插槽、作用域插槽
子组件中:
插槽用 标签来确定渲染的位置,里面放如果父组件没传内容时的后备内容
具名插槽用name属性来表示插槽的名字,不传为默认插槽
作用域插槽在作用域上绑定属性来将子组件的信息传给父组件使用,这些属性会被挂在父组件slot-scope接收的对象上

//Child.vue
<template>
	<div>
		<main>
		//默认插槽
			<slot>
				//slot内为后备内容
				<h3>没传内容</h3>
			</slot>
		</main>
		
		//具名插槽
		<header>
			<slot name="header">
				<h3>没传header插槽</h3>
			</slot>
		</header>

		//作用域插槽
		<footer>
			<slot name="footer" testProps="子组件的值">
			 <h3>没传footer插槽</h3> 
			</slot> 
		</footer>
	</div>
</template>

<style scoped>
div{
	border:1px solid #000;
}
</style>

父组件

  • 默认插槽的话直接在子组件的标签内写入内容即可
  • 具名插槽是在默认插槽的基础上加上slot属性,值为子组件插槽name属性值
  • 作用域插槽则是通过slot-scope获取子组件的信息,在内容中使用。这里可以用解构语法去直接获取想要的属性
// Parent.vue
<child>
  <!-- 默认插槽 -->
  <div>默认插槽</div>  
  <!-- 具名插槽 -->
  <div slot="header">具名插槽header</div>
  <!-- 作用域插槽 -->
  <div slot="footer" slot-scope="slotProps">
    {{slotProps.testProps}}
  </div>
</child>

<think>我们正在讨论Vue3中件之间的方式。根据提供的引用,我们可以总结出几种常见的方式: 1. 使用Props(父子):父件通过属性绑定向子递数据,子件通过props接收。 2. 使用自定义事件(子父):子件通过触发自定义事件,父件监听该事件并更新数据。 3. 使用`useAttrs`(父子):Vue3中提供了`useAttrs`函数,可以获取父递的所有属性(包括事件),类似于Vue2中的`$attrs`和`$listeners`。 4. 通过父件作为中介(兄弟件通信):例如,子件A通过事件将数据给父件,父件再通过props将数据递给子件B。 此外,Vue3还有其他方式,比如: 5. 使用provide/inject(祖先件向后代):适用于跨层级件通信。 6. 使用Vuex/Pinia(状态管理):全局状态管理,任意件之间都可以通信。 7. 使用事件总线(Event Bus):但Vue3中移除了$on、$off等方法,可以使用第三方库如mitt来实现。 8. 使用ref获取子件实例:父件通过ref获取子件的实例,然后直接调用子件的方法或访问数据。 下面我们根据引用中的示例,详细说明几种方式: 一、Props(父子) 引用[2]和引用[3]都展示了Props的用法。父件在子件标签上绑定属性,子件通过props选项接收。 父件: ```vue <template> <son :isShow="data.isShow"></son> </template> <script> import son from '../components/son.vue' import { reactive } from 'vue' export default { components: { son }, setup() { let data = reactive({ isShow: false }); return { data } } } </script> ``` 子件: ```vue <template> <div class="menu">{{ isShow }}</div> </template> <script> export default { props: { isShow: Boolean }, setup(props) { // 使用props.isShow } } </script> ``` 二、自定义事件(子父) 引用[5]展示了子件触发事件,父件监听事件并处理。 子件A(ChildA): 假设在ChildA中触发一个事件,递数据给父件: ```vue <script setup> import { defineEmits } from 'vue' const emits = defineEmits(['value-changed']) // 某个方法中触发事件 function changeValue() { emits('value-changed', 'new value') } </script> ``` 父件: ```vue <template> <ChildA @value-changed="handleValueChanged" /> <ChildB :value="valueFromChildA" /> </template> <script> import { ref } from 'vue' export default { setup() { const valueFromChildA = ref('') function handleValueChanged(value) { valueFromChildA.value = value } return { handleValueChanged, valueFromChildA } } } </script> ``` 三、useAttrs(父子) 引用[1]提到,在Vue3中可以使用`useAttrs`来获取父递的属性和事件(包括自定义事件和原生事件)。 子件: ```vue <script setup> import { useAttrs } from 'vue' const attrs = useAttrs() // attrs包含了父递过来的所有属性和事件(除了子件已声明的props) </script> ``` 四、provide/inject(跨层级) 没有在引用中直接出现,但也是Vue3中常用方式。 祖先件: ```vue <script setup> import { provide } from 'vue' provide('key', 'value') </script> ``` 后代件: ```vue <script setup> import { inject } from 'vue' const value = inject('key') </script> ``` 五、兄弟件通信(通过父件中转) 如引用[5]所示,子件A通过事件给父件,父件再通过props给子件B。 六、使用ref获取子件实例 父件可以通过ref获取子件的实例,然后直接访问子件的属性或方法。 父件: ```vue <template> <Child ref="childRef" /> </template> <script setup> import { ref } from 'vue' const childRef = ref(null) // 在需要的时候访问子件 function callChildMethod() { childRef.value.childMethod() } </script> ``` 子件需要暴露方法: ```vue <script setup> import { defineExpose } from 'vue' function childMethod() { // ... } defineExpose({ childMethod }) </script> ``` 七、使用事件总线(Event Bus) 可以使用第三方库mitt: 安装mitt:`npm install mitt` 创建事件总线(eventBus.js): ```js import mitt from 'mitt' const emitter = mitt() export default emitter ``` 件A(发送事件): ```js import emitter from './eventBus' emitter.emit('event-name', data) ``` 件B(接收事件): ```js import emitter from './eventBus' emitter.on('event-name', (data) => { // 处理数据 }) ``` 八、使用状态管理(Vuex或Pinia) 这里以Pinia为例(Vue3官方推荐的状态管理库): 创建store,然后在任何件中导入使用。 以上是Vue3中的常见方式,根据不同的场景选择合适的方式。 相关问题: 1. Vue3中如何实现跨层级2.Vue3中,如何通过ref获取子件实例并调用其方法? 3. Vue3中如何使用事件总线(Event Bus)进行件通信? 4. Vue3的Props和Vue2有什么不同之处? 5.Vue3的setup语法糖中,如何定义props和emits? </think>在 Vue 3 中,主要有以下 7 种方式,结合引用内容说明如下: ### 一、Props 父子(最常用) ```vue <!-- 父件 Parent.vue --> <template> <Child :msg="message" /> </template> <script setup> import Child from './Child.vue' const message = ref('Hello from parent') </script> <!-- 子件 Child.vue --> <template> <div>{{ msg }}</div> </template> <script setup> defineProps({ msg: { type: String, default: "" } }) </script> ``` **特点**:单向数据流,类型验证,需显式声明接收[^3][^4] ### 二、自定义事件(子父) ```vue <!-- 子件 Child.vue --> <template> <button @click="sendData">递数据</button> </template> <script setup> const emit = defineEmits(['data-change']) const sendData = () => emit('data-change', { value: 123 }) </script> <!-- 父件 Parent.vue --> <template> <Child @data-change="handleData" /> </template> <script setup> const handleData = (payload) => console.log(payload.value) // 123 </script> ``` **特点**:通过`defineEmits`声明事件,`emit()`触发[^5] ### 三、useAttrs(透属性/方法) ```vue <!-- 父件 --> <Child @click="handleClick" title="提示文本" /> <!-- 子件 --> <script setup> import { useAttrs } from 'vue' const attrs = useAttrs() console.log(attrs.title) // "提示文本" // 可访问所有透属性和事件(含原生DOM事件) </script> ``` **特点**:获取未在 props 中声明的属性和事件,类似 Vue2 的`$attrs`[^1] ### 四、v-model 双向绑定 ```vue <!-- 父件 --> <Child v-model:name="userName" /> <!-- 子件 --> <script setup> defineProps(['name']) defineEmits(['update:name']) const update = () => emit('update:name', 'newValue') </script> ``` **特点**:Vue3 支持多个`v-model`绑定(如`v-model:first-name`) ### 五、provide/inject(跨级通信) ```vue <!-- 祖先件 --> <script setup> import { provide } from 'vue' provide('globalToken', 'auth_key') </script> <!-- 后代件 --> <script setup> import { inject } from 'vue' const token = inject('globalToken') // 'auth_key' </script> ``` **特点**:解决多级件数据递问题 ### 六、ref 获取件实例 ```vue <!-- 父件 --> <template> <Child ref="childRef" /> </template> <script setup> import { ref } from 'vue' const childRef = ref(null) childRef.value.childMethod() // 调用子件方法 </script> <!-- 子件 Child.vue --> <script setup> defineExpose({ // 暴露方法 childMethod: () => console.log('方法被调用') }) </script> ``` **特点**:需子件用`defineExpose`显式暴露 ### 七、状态管理(Pinia/Vuex) ```js // store.js import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => ({ count: 0 }) }) // 任意件 const store = useStore() store.count++ // 全局共享状态 ``` **特点**:复杂应用推荐方案 --- ### 选择建议 1. **父子件**:Props + 自定义事件 2. **兄弟件**:通过共同父件中转 或 Pinia 3. **跨层级**:provide/inject 4. **模板透**:useAttrs 5. **双向绑定**:v-model 6. **全局状态**:Pinia > 注:Vue3 移除`$listeners`,相关功能已整合到`useAttrs`中[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值