Vue-组件间传值方式

一、$emit传值[父传子和子传父]

1、首先创建好父子组件和eventBus.js事件监听
image.png
1.0、在父组件的操作=>父传子
<template>
  <div class="fuqin">
    <h1>父视图</h1>
    <button @click="fuclick">父视图按钮点击穿值给子视图</button>
    <ZiShiTu class="zishitu"></ZiShiTu>
  </div>
</template>
<script>
import ZiShiTu from './ZiShiTu.vue'//引入子视图
import connect from '../js/eventBus'//引入js
export default {
    data() {
        return {
            zhuname: '高启强',
            usname: '高启盛',
            hhname: '唐小龙',
            kkkl: '唐小虎',
        }
    },
    components: {
        ZiShiTu
    },
    methods: {
        fuclick() {//触发
            // 点击按钮将参数传递给子视图
            connect.$emit("activeName", this.zhuname, this.usname, this.hhname, this.kkkl);
        },
    },
}
</script>
1.1、在子组件中接收父视图发过来的参数
//同理
import connect from '../js/eventBus'
。。。。
  created() {
    //    接收从父视图传过来的参数
        connect.$on('activeName', (item0, item1, item2, item3) => {
            console.log('从父视图传过来的值:', item0, item1, item2, item3);
        });
    },
结果打印.png
2、在子组件的操作=>子传父
<template>
  <div>
    <h1>子视图</h1>
    <button @click="changeFather">子视图按钮点击穿值给父视图</button>
  </div>
</template>
<script>
export default {
    data() {
        return {
            dianying: '狂飙',
            dianshiju: '铁道有熊队',
            zongyi:'奔跑吧!code'
        }
    },
    created() {
    },
    methods: {
        changeFather() {//触发按钮将值传给父视图
            this.$emit("changeEvent", this.dianying);
        }
    },
}
</script>
2.1、在父视图中接收操作

在父视图中接收操作.png
从子视图传递过来的值.png
打印log.png
上面示例代码已放github

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容