vue 实现,子组件向父组件 传递数据

首先理清组件之间的关系

    组件与组件之间,还存在着不同的关系。父子关系与兄弟关系(不是父子的都暂称为兄弟吧)。

  父子组件

      父子关系即是组件 A 在它的模板中使用了组件 B,那么组件 A 就是父组件,组件 B 就是子组件。

先写子组件:

绑定一个单击事件

   <el-button type="primary" icon="el-icon-search" @click="search"  style="background: #5b6270; border: none;">搜索</el-button>

定义数组:用来存值,然后传递给父组件

export default {
        data() {
            return {
                childByValue:[]   //先定义一个数组
            };
        }
  }
methods: {
            search: function() {
                const inp = this.input;
                if (inp ==="") {
                    this.selectAll(); //如果为空 则执行selectAll去
                } else {
                    this.$axios.get('http://localhost:9999/search?productName=' + inp).then(res => {
                        if (res.data === "error") {
                            alert("抱歉,没有查询到你需要的商品");
                        } else {
                            this.childByValue = res.data;      //给数组赋值
                            this.$emit('childByValue', this.childByValue) //发射、广播出去 主要这里
                        }
                    })
                }
            }
    }

然后子组件就写完了

父组件:

使用components      翻译就是:组成的意思

import headers from './Head.vue'   //导入子组件
    export default {
        components: {
            headers: headers   //这里是import 导入的名字一致
        }
    }

使用子组件

    <headers @childByValue="childByValue"></headers>

截图:

另外 还需要绑定事件来接受数据

methods: {
            childByValue(value) { 
                console.log(value);//接收子组件的数据然后你想干嘛就干嘛
            }
        }
原文地址:https://www.cnblogs.com/nongzihong/p/10287211.html