彪码 Vue3父子传值 、兄弟传值

本文详细介绍了Vue3中父子组件的传值方法,包括使用props从父组件向子组件传递数据,以及通过事件触发器实现子组件向父组件的通信。同时,还展示了如何通过事件总线实现兄弟组件之间的通信,以实现动态数据的共享。通过实例代码演示了整个过程,帮助理解Vue3组件间的通信机制。

父子传值

在我们的项目当中 , 会出现我们页面里面嵌套一些组件的情况,但是我们想要让组件内部的数据成为动态的 , 这个时候 我们就要用到我们的父子传值,

Vue3  父向子传值

首先我们定义了一个组件,在父组件里面进行引用

<template>
  <div>
    父组件:{{parentStr}}
    <Child :msg="parentStr"></Child>
  </div>
</template>
<script>
import Child from "../components/Child.vue";
import { ref } from "vue";
export default {
  components: { Child },
  data() {
    const parentStr = ref("父组件的值");

    return {
      parentStr,
    };
  },
};
</script>

子组件:

<template>
  <div>
    子组件:{{msg}}
    <button>点击</button>
  </div>
</template>
<script>
import { computed, ref } from "vue";
export default {
  components: {},
  props: { msg: String },
  setup(props, ctx) {
    const msg = computed(() => {
      return props.msg;
    });
    return {
      msg,
    };
  },
};
</script>

这个时候我们页面效果是:

 这个时候值就成功的传到了子组件里,

属性
props它是响应式的,里面包含了父组件传递过来的信息,
context普通的JavaScript对象,暴露了在setup里面可能有用的一些方法
computed计算属性,监听值发生改变了进行同步,没有改变走缓存

子向父传值

子组件

<template>
  <div>
    子组件:{{msg}}
    <button @click="setParentStr">点击</button>
  </div>
</template>
<script>
import { computed, onMounted, ref } from "vue"
export default {
  components: {},
  props: { msg: String },
  setup(props, ctx) {
      //子向父传值的方法
    const setParentStr = () => {
      ctx.emit("parentStr", "点击成功");
    };

    const msg = computed(() => {
      return props.msg;
    });

   
    return {
      msg,setParentStr
    };
  },
};
</script>

这里是给我们的按钮添加了一个点击事件,在点击的时候触发setParentStr方法,在setup里面定义了方法 , 一定要在 return 抛出, ctx.emit("传递名称",传过去的值)

父组件

<template>
  <div>
    父组件:{{parentStr}}
    <Child :msg="parentStr" @parentStr="appectStr"></Child>
  </div>
</template>
<script>
import Child from "../components/Child.vue";
import { ref } from "vue";
export default {
  components: { Child },
  data() {
    const parentStr = ref("父组件的值");
    const appectStr=(val)=>{
parentStr.value=val
    }
    return {
      parentStr,appectStr
    };
  },
};
</script>

我们在接收值得时候 利用 @子组件传递的名称="触发的方法名称",这样在我们的方法里就能进行操作我们传递的值

效果图

 兄弟传值 

由于子组件 的值是父组件传递过去的 , 所以 这个兄弟组件 操作了父组件的值,那么子组件也跟着变化  代码如下

父组件 引入 兄弟组件

<template>
  <div>
    父组件:{{parentStr}}
    <Child :msg="parentStr" @parentStr="appectStr"></Child>
    <ChildBrother @setChildStr="setChildStr"></ChildBrother>
  </div>
</template>
<script>
import Child from "../components/Child.vue";
import { ref } from "vue";
import ChildBrother from '../components/childBrother'
export default {
  components: { Child,ChildBrother },
  data() {
    const parentStr = ref("父组件的值");
    const appectStr=(val)=>{
parentStr.value=val
    }
    const setChildStr=(val)=>{
parentStr.value=val
    }
    return {
      parentStr,appectStr,setChildStr
    };
  },
};
</script>

ChildBrother 兄弟组件

<template>
  <div>兄弟组件:{{Str}}
<button @click="setBrotherStr">点点</button>

  </div>
</template>

<script>
import { ref } from "vue";
export default {
  props: {},
  setup(props,ctx) {
    const Str = ref("我是兄弟组件");
    const setBrotherStr=()=>{
      ctx.emit('setChildStr','我是兄弟组件传过来的值')
    }
    return {
      Str,setBrotherStr
    }
  }
}
</script>

效果图

 那怎么把兄弟组件的值直接传给子组件呢

这个时候我们需要下载一个插件

npm install --save vue3-eventbus

安装完毕 在main.js里面进行挂载

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import eventBus from 'vue3-eventbus'//引入vue3-eventbus

createApp(App).use(eventBus).use(store).use(router).mount('#app')

Child 子组件

<template>
  <div>
    子组件:{{ChildStr}}
    <button @click="setParentStr">点击</button>
  </div>
</template>
<script>
import {  ref } from "vue"
import bus from 'vue3-eventbus'
export default {
  components: {},
  props: {  },
  setup(props, ctx) {
    const ChildStr = ref('Child的值')
    bus.on('setChildStr',(val)=>{
      ChildStr.value=val
    })
    return {
      ChildStr
    };
  },
};
</script>

兄弟组件 ChildBrother

<template>
  <div>兄弟组件:{{Str}}
<button @click="setChildStr">点点</button>
  </div>
</template>

<script>
import { ref } from "vue";
import bus from 'vue3-eventbus'
export default {
  props: {},
  setup(props,ctx) {
    const Str = ref("我是兄弟组件")
    const setChildStr=()=>{
      bus.emit('setChildStr','我是兄弟组件传过来的值')
    }
    return {
      Str,setChildStr
    }
  }
}
</script>

在这两个文件里面 分别引入 vue3-eventbus 这个插件 

传递:bus.emit('传递名称',传递的值)

接收:  bus.on('传递名称',(传递的值)=>{

要进行的操作

})

效果图下方

 战士的意志要像礁石一样坚定 战士的性格要像和风一样温柔
 

Vue 3 中,父子组件之间的数据传递是构建组件化应用的核心部分。以下是几种常用的父子组件方法,结合不同场景和需求,可以灵活选择适合的方式。 ### 3.1 使用 `props` 实现父子 父组件通过 `props` 向子组件传递数据。在子组件中使用 `defineProps` 定义接收的属性,并在模板中使用这些属性。这种方式适用于静态或动态的单向数据流。 示例代: ```vue <!-- 子组件 ChildComponent.vue --> <script setup> const props = defineProps({ message: String, count: Number }); </script> <template> <p>来自父组件的消息:{{ message }}</p> <p>来自父组件的数字:{{ count }}</p> </template> ``` 父组件使用方式: ```vue <!-- 父组件 ParentComponent.vue --> <script setup> import ChildComponent from &#39;./ChildComponent.vue&#39;; </script> <template> <ChildComponent message="Hello Vue 3" :count="42" /> </template> ``` ### 3.2 使用 `defineEmits` 实现子子组件通过 `$emit` 触发事件,向父组件传递数据。在 Vue 3 的 `setup` 语法中,使用 `defineEmits` 来定义并触发事件。 示例代: ```vue <!-- 子组件 ChildComponent.vue --> <script setup> const emit = defineEmits([&#39;update&#39;]); function sendDataToParent() { emit(&#39;update&#39;, &#39;来自子组件的新数据&#39;); } </script> <template> <button @click="sendDataToParent">发送数据给父组件</button> </template> ``` 父组件监听事件: ```vue <!-- 父组件 ParentComponent.vue --> <script setup> import ChildComponent from &#39;./ChildComponent.vue&#39;; function handleUpdate(data) { console.log(&#39;接收到子组件的数据:&#39;, data); } </script> <template> <ChildComponent @update="handleUpdate" /> </template> ``` ### 3.3 使用 `provide/inject` 实现深层 当需要在嵌套较深的父子组件之间传递数据时,可以使用 `provide` 和 `inject`,这种方式避免了逐层传递 `props`。 示例代: ```vue <!-- 祖先组件 --> <script setup> import { provide, ref } from &#39;vue&#39;; const sharedData = ref(&#39;共享数据&#39;); provide(&#39;sharedData&#39;, sharedData); </script> ``` 后代组件使用 `inject` 接收数据: ```vue <!-- 后代组件 --> <script setup> import { inject } from &#39;vue&#39;; const sharedData = inject(&#39;sharedData&#39;); </script> <template> <p>接收到的共享数据:{{ sharedData }}</p> </template> ``` ### 3.4 使用 `defineProps` 和 `defineEmits` 进行类型校验(TypeScript 支持) Vue 3 支持使用 TypeScript 对 `props` 和 `emits` 进行类型校验,从而提升代的可维护性和健壮性。 示例代: ```vue <script setup lang="ts"> // 定义 props 类型 defineProps<{ message: string; count?: number; }>(); // 定义 emit 类型 const emit = defineEmits<{ (e: &#39;update&#39;, value: string): void; (e: &#39;delete&#39;): void; }>(); </script> ``` ### 3.5 避免 `props` 的深度监听问题 当传递的是一个对象或数组时,如果需要监听其内部变化,可以使用 `watch` 并设置 `deep: true`。 ```ts watch(() => props.obj, (newVal) => { // 处理对象变化 }, { deep: true }); ``` ### 3.6 动态组件如何保持状态 使用 `<KeepAlive>` 包裹动态组件可以保留其状态,避免重复渲染带来的性能损耗。 ```vue <KeepAlive> <component :is="currentComponent" /> </KeepAlive> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值