zoukankan      html  css  js  c++  java
  • vue 子组件给父组件传值

    在vue中是通过自定义事件来实现的,子组件使用$emit()方法触发事件,父组件使用v-on指令监听子组件的自定义事件来完成通讯的:

    $emit()方法的语法形式如下:

    vue.$emit(eventName,[...args])

    eventName是自定义事件名称 ,args是附加的参数

    父组件:

    <template>
      <div>
        <div>{{val1}}</div>
        <div v-for="(item,index) in val2" :key="index">{{item}}</div>
        
        <!--v-on的简写@-->
        <!--<emit-component v-on:handleClick="getVal"></emit-component>-->
        <!--@handleClick="getVal"  相当于一个事件,有事件就有方法-->
        <emit-component @handleClick="getVal"></emit-component>
      </div>
    </template>
    
    <script>
    import emitComponent from "@/components/emitComponent";
    export default {
      name: "emit",
      components:{
        emitComponent
      },
      data(){
        return{
          val1:'',
          val2:[]
        }
      },
      methods:{
        //接收参数。传几个就接几个
        getVal(val1,val2){
          this.val1 = val1;
          this.val2 = val2
        }
      }
    };
    </script>
    
    <style scoped>
    </style>

    子组件

    <template>
      <div>
        <div>
          <button type="button" @click="handleClick">点击给父组件传值</button>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: "emitComponent",
      data() {
        return {
          userList:['张三','李四','王五']
        }
      },
      methods: {
        handleClick() {
          //向父组件传值
          this.$emit('handleClick','我是子组件值1',this.userList) //可以一次传多个(对象,数组,字符串,等)
        }
      }
    }
    </script>
    
    <style scoped>
    
    </style>
  • 相关阅读:
    LeetCode:数组(三)
    LeetCode:数组(二)
    LeetCode:数组(一)
    python实现栈的基本操作
    python基本内置函数
    Pycharm的常见Debug调试方法(持续更新)
    计算广告系列(一)-基本概念整理
    es与solr对比
    数据库优化
    java线程池
  • 原文地址:https://www.cnblogs.com/ssjd/p/14544013.html
Copyright © 2011-2022 走看看