vue父子组件传值

参考

父组件


<div class="formRight">
	<div class="formRightLuckysheet">
		<preview :id="businessId" :tableTemplateId1="tableTemplateId" ref="luckysheetPreview" />
	</div>
</div>

子组件

props: {
	id: { type: String },
	tableTemplateId1: {type: String},
	modal: { type: String }
},

父亲调用孩子的方法
父组件

<el-button type="primary" icon="el-icon-caret-right" @click="nextPage">下页</el-button>

// luckysheetPreview 是子组件的refs(相当于id) 
// nextPage方法在子组件里面
this.$refs.luckysheetPreview.nextPage()

子方法

nextPage() {
      window.luckysheet.showLoadingProgress()
      // 切换页码前,先保存当前页的动态区域数据
      this.getDyncVal()
      const originPageNo = this.pageNo
      this.pageNo = this.pageNo + 1
      // 判断是否有下一个sheet
      const sheetCount = window.luckysheet.getAllSheets().length
      if (sheetCount < this.pageNo) {
        // 下一个sheet不存在,则复制一个
        const name = '第' + (this.pageNo) + '页'
        window.luckysheet.setSheetCopy()
        window.luckysheet.setSheetName(name)
      }
      // 因为sheet的下标从0开始,所以减1
      window.luckysheet.setSheetActive(originPageNo, { success: this.nextPageSuccess })
    },

子组件调用父组件方法

<template>
    <div>
        <div>父组件通过字符串方式传过来的title --- {{title}}</div>
        <button @click="parentFun()">调用父组件的方法</button>
        <div>通过父组件传过来的父组件对象调用的父组件的属性msg --- {{parent.msg}}</div>
        
        <button @click="sendMsgToParent()">点击向父组件传值</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                msg: '这是子组件的msg'
            }
        },
        props: {
            /* 4.通过属性接收父组件传过来的数据,属性是parent-fun, props中可以使用parentFun变量接收 */
            title,
            parentFun,
            parent
        },
        methods: {
            sendMsgToParent() {
                //1.子组件通过子定义事件child-msg的方式将msg传给父组件
                this.$emit('child-msg', this.msg)
            }
        }
    }
    
</script>
<template>
    <div>
        <!-- 使用子组件,通过属性向子组件传值 -->
        <!-- 2.父组件通过监听子组件自定义的@child-msg事件获取子组件传过来的数据 -->
        <child @child-msg="getChildMsg" title="父组件传过来的title" :parent-fun="parentFun" :parent="this"></child>
    </div>
</template>

<script>
    //1. 引入子组件
    import child from './child.vue'
    export default {
        data() {
            return {
                parentMsg: '这是父组件的msg'
            }
        },
        //2.在父组件的components中注册子组件
        components: {
            child
        },
        methods: {
            parentFun() {
                console.log("这是父组件的方法");
            },
            getChildMsg(msg) {
                console.log("这就是子组件传过来的msg" + msg)
            }
        }
    }
</script>
posted @   Kelvin's  阅读(144)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2021-07-22 项目git使用流程图
点击右上角即可分享
微信分享提示