zoukankan      html  css  js  c++  java
  • vue 父子组件相互传参

    转自https://blog.csdn.net/u011175079/article/details/79161029

    子组件:

    <template>
        <div>
            <div>{{count}}</div>
            <div v-for="(item, index) in list">{{item}}</div>
        <button v-on:click="sendMsg">向父组件传参</button>  <!-- 这里用简单的绑定方法触发传参-->
        </div>
    </template>
     
    <script>
    export default {
      name: 'main_header',
      props: ['count', 'list'],
      methods: {
        sendMsg: function () { //传参方法
          this.$emit('headCallBack', '子组件的参数内容'); //第一个参数是父组件中v-on绑定的自定义回调方法,第二个参数为传递的参数
        }
      }
    };
    </script>
     
    <style>
    </style>

    父组件:

    <template>
      <div id="app">
        <img src="./assets/logo.png">
        <div>子组件传过来的内容:{{msg}}</div>
        <mainHeader :count="count" :list="list" v-on:headCallBack="headCall"></mainHeader> <!--通过v-on绑定方法,headCallBack为子组件中$emit()中第一个参数,headCall为回调方法,参数就传入这个方法中,看下面的方法-->
        <router-view/>
      </div>
    </template>
     
    <script>
    import mainHead from './components/header/main_header';
    var data = {
      list: ['java', 'html', 'css', 'js']
    };
    export default {
      name: 'app',
      data: function () {
        return {
          count: 0,
          list: data.list,
          msg: ''
        };
      },
      components: {
        mainHeader: mainHead
      },
      methods: {
        addCount: function () {
          let _this = this;
          setInterval(function () { _this.count++; }, 1000);
        },
        headCall: function (msg) { //回调方法,接收子组件传的参数
          this.msg = msg;
        }
      },
      mounted: function () {
        this.$nextTick(function () {
          this.addCount();
        });
      }
    };
    </script>

    总结一下:

    子组件向父组件传参

    • 子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
    • 将父组件中v-on:后事件名称作为$emit的第一个参数,需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
    • 在父组件中注册子组件,并在子组件标签上绑定对自定义事件的监听

    父组件向子组件传参

    • 父组件定义属性值
    • 子组件先声明对应的props:['属性名'],之后使用此属性时,可向使用自身元素一样使用父组件的元素
  • 相关阅读:
    springboot 集成jsp
    eclipse 创建 springboot项目
    eclipse 导入别人拷贝过来的工作空间项目
    vue安装及使用
    eclipse配置svn导出项目
    sql为什么用0,1表示男女?在sql语句里转好还是在页面转好?
    svn下载多模块及依赖框架的项目
    django连接sqlserver
    字符编码
    数组希尔排序法
  • 原文地址:https://www.cnblogs.com/duanzhenzhen/p/10449176.html
Copyright © 2011-2022 走看看