• vue的子传父


    子组件传值给父组件,需要触发一个事件。

    在这个事件里,使用this.$emit("父组件使用的名称","子组件的数据")

    在父组件中引用的子组件,在子组件的标签中用@父组件使用的名称="父组件里面的一个方法名($event)"

    在父组件里使用刚刚定义的方法,父组件里面的一个方法名(data)

    代码如下:

    子组件代码:

    <template>
    <div>
      <!-- 定义一个事件,触发这个事件,才能传值给父组件 -->
        <button @click="trans()">点击按钮传递值</button>
         
    </div>
    </template>
    <script>
    export default {
      name: "Child",
      data () {
        return {
            childData:"childData"
        };
      },
      methods:{
          trans(){
            //this.$emit("父组件要触发的事件名称","需要传递的数据")
              this.$emit("transData",this.childData);
          }
      }
    }
    </script>
    <style lang="css" scoped>
    </style>

    父组件代码:

    <template>
    <div>
        <!-- 父组件中引入子组件,定义一个方法,@子组件中$emit里的事件名,并传入$event -->
        <child @transData="getChildData($event)"></child>
        {{parentData}}
    </div>
    </template>
    <script>
    import Child from '../components/Child.vue'
    export default {
      name: "Parent",
      components:{
          Child
      },
      data () {
        return {
            parentData:"parentData"
        };
      },
      methods:{
        //   实现父组件方法
          getChildData(data){
              this.parentData = data;
          }
      }
    }
    </script>
    <style lang="css" scoped>
    </style>
  • 相关阅读:
    洛谷P2402 奶牛隐藏
    BZOJ2150: 部落战争
    HDU 6405 Make ZYB Happy(广义SAM)
    CodeForces
    2019CCPC秦皇岛 E题 Escape(网络流)
    2019CCPC秦皇岛D题 Decimal
    2019CCPC秦皇岛I题 Invoker(DP)
    2019CCPC秦皇岛 F Forest Program
    2019CCPC秦皇岛 J MUV LUV EXTRA(KMP)
    2019CCPC秦皇岛 K MUV LUV UNLIMITED(博弈)
  • 原文地址:https://www.cnblogs.com/luguankun/p/10600614.html
Copyright © 2020-2023  润新知