• Vue父子组件之间传值


    一、父组件向子组件传值:

    1. 在父组件中调用子组件时,使用v-bind将要传的值进行绑定
      <com :parentmsg="msg"></com>
    2. 在子组件的props中,添加第一步中为接收父组件数据而定义的变量
      props: ["parentmsg"]
    3. 子组件可使用 this.parentMsg 来调用父组件的数据 msg

    二、子组件向父组件传值:

    1. 父组件中先定义一个方法a用来获取子组件的值
      methods: {
                      getChildMsg (data) {
                          this.childMsg = data
                      }
                  },
    2. 在父组件中调用子组件时,将父组件的那个方法与子组件中的一个方法b绑定
              <com :parentmsg="msg" @func='getChildMsg'></com>
    3. 在子组件中定义另一个方法c来处理用于绑定父组件方法的方法b,方法c 使用 $emit,第一个参数为方法b的名称,第二个参数为要传递给父组件的值
      methods: {
                      sendToParent () {
                          this.$emit('func', this.msg)
                      },
                  },
    4. 在子组件中用合适的方法调用 c 实现向父组件传值
      created() {
                      this.sendToParent()
                  },
    5. 父组件可使用 this.childMsg 来调用子组件的数据 msg

    实例代码:

     1 <body>
     2     <div id="app">
     3         <com :parentmsg="msg" @func='getChildMsg'></com>
     4         <!-- 在父组件中可调用子组件中的数据 -->
     5         <h2>{{childMsg}}</h2>
     6     </div>
     7 
     8     <template id="tmp">
     9         <div>
    10             <!-- 在子组件中可调用父组件中的数据 -->
    11             <h1>子元素模板---{{parentmsg}}</h1>
    12         </div>
    13     </template>
    14 
    15     <script>
    16         // 创建模板
    17         let com = {
    18             template: '#tmp',
    19             data() {
    20                 return {
    21                     msg: "子组件中的数据"
    22                 }
    23             },
    24             methods: {
    25                 sendToParent () {
    26                     this.$emit('func', this.msg)
    27                 },
    28             },
    29             created() {
    30                 this.sendToParent()
    31             },
    32             props: ["parentmsg"]
    33         }
    34 
    35         // 创建Vue实例
    36         let vm = new Vue({
    37             el: "#app",
    38             data: {
    39                 msg: "父组件中的数据",
    40                 childMsg: ''
    41             },
    42             methods: {
    43                 getChildMsg (data) {
    44                     this.childMsg = data
    45                 }
    46             },
    47             components: {
    48                 com
    49             }
    50         })
    51     </script>
    52 </body>
  • 相关阅读:
    致DBA:为什么你经常犯错,是因为你做的功课不够
    Hbase的shell命令学习
    mysql通过拷贝文件实现数据快速迁移实例
    项目领导力学习总结
    放权,从鞋柜开始
    不抱怨的世界
    定投我们自己
    mysql core文件的正确打开姿势
    2017小目标
    世界是有生命的(通向财富自由之路学习笔记十五)
  • 原文地址:https://www.cnblogs.com/Ryan368/p/11331801.html
Copyright © 2020-2023  润新知