快速掌握Vue中父子组件传值,兄弟组件中传值。

您所在的位置:网站首页 vue父子组件间传值 快速掌握Vue中父子组件传值,兄弟组件中传值。

快速掌握Vue中父子组件传值,兄弟组件中传值。

2024-06-17 05:19| 来源: 网络整理| 查看: 265

在Vue-cli项目中,项目组件间的关系有父子组件和兄弟组件,组件间的传值就是一个经常要用到的知识点,本次就让我们一起看看Vue中 各个组件间是如何实现传值操作的。

为了方便这里我们以App.vue作为父组件

首先了解一下目录结构

                                        

第一:父组件向子组件传值

 父组件向子组件传值需要用到Props,通过自定义Props的值用v-bind 绑定到子组件标签上的方式传递数据。

父组件代码:

import son from "./components/son.vue"; export default { name: "App", data() { return { cont:"我是父组件中的数据" } }, components: { son, }, }; #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; }

子组件中的代码:

{{items}} export default { data() { return { } }, props:["items"] }

子组件用props接受父组件传来的值,并渲染在页面上

子向父传值时就需要用到自定义事件,通过触发子组件自定义的事件向父组件传递数据 

 子组件内的代码:

{{items}} 点击修改 export default { data() { return { } }, props:{ items:{ type:String, default:"" } }, methods: { aa(){ this.$emit('changes',"我是被修改的值","我是传递过去的值") } }, }

子组件定义了一个 ‘changes’的事件 

父组件中:

import son from "./components/son.vue"; export default { name: "App", data() { return { cont:"我是父组件中的值" } }, components: { son, }, methods: { changes(){ this.cont = "我是被修改的数据" } }, }; #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; }

触发该事件 :

  父子组件传值就到这

接下来是兄弟组件间的传值

 兄弟组件间的传值需要用到Vue实例中的 $emit 和 $on 方法

main.js中的配置:

import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false export const eventBus = new Vue(); //用于导出vue实例 new Vue({ render: h => h(App), }).$mount('#app')

在border组件中 和 son组件中都要引入eventBus 模块

在border组件中:

border点击向son组件传值 import { eventBus } from "../main"; export default { data() { return { itemss:"我是border组件中的值" } }, methods: { cz(){//向兄弟组件传值方法 eventBus.$emit("eventone",this.itemss) } }, created() { eventBus.$on("cztwo",(num)=>{ console.log(num); }) }, }

在son组件中:

{{ items }} 点击修改 son点击向border组件传值 import { eventBus } from "../main"; export default { data() { return { ccc: "我是son组件传递的值", }; }, props: { items: { type: String, default: "", }, }, methods: { aa() { this.$emit("changes", "我是被修改的值", "我是传递过去的值"); }, cz() { //向兄弟组件传值方法 eventBus.$emit("cztwo", this.ccc); }, }, created() { eventBus.$on("eventone", (num) => { console.log(num); }); }, };

效果:

 在控制台中 我们看到了兄弟组件中的值已经互相拿到了。

其实在父子组件传值,兄弟组件传值中 还有一个更重要的方法就是利用vuex来进行传值

 本期知识点就分享这了,谢谢观看!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3