zoukankan      html  css  js  c++  java
  • vue 组件之间数据传递(七)

    1、props:父组件 -->传值到子组件
     app.vue是父组件 ,其它组件是子组件,把父组件值传递给子组件需要使用 =>props

    在父组件(App.vue)定义一个属性(变量)sexVal = '男' 把该值传递给 子组件(B.vue),如下:

    App.vue
    <template>
      <div id="app">
        <!--<router-view></router-view>-->
      <parentTochild :sex="sexVal"></parentTochild>
        </div>
    </template>
    
    <script>
      import parentTochild from  './components/B'
      export default {
        name: 'app',
        data: function () {
         return {
            sexVal:""
         }
        },
        methods: {
    
        },
        components: {
          parentTochild
        }
    
      }
    </script>

    B.vue

    <template>
      <div class="b_class">  <!--外边只允许有一个跟元素-->
          <p>父组件传值给子组件</p>
          <p>姓名:{{name}}</p>
          <p>年龄:{{age}}</p>
          <p>sex:{{sex}}</p>
    
      </div>
    </template>
    <script>
      export default {
        data: function () {
          return {
            name: 'zs',
            age: 22
          }
        },
        props:['sex']
      }
    </script>

    tips:

    在父传值给子组件使用属性值:props; 理解成 “ 中介”  父组件绑定传递属性值(:sex="sexval") 子组件 获取属性值 props['sex'] 会添加到data 对象中


    2、$emit:
    子组件 -->传值到父组件

    在B.vue 子组件添加一个点击事件为例子
     @click="sendMs

    <input type="button" @click="sendMsg" value="子组件值传父组件">

    在调用该函数后使用$emit方法传递参数 (别名,在父组件作为事件名称, 值); 

      methods: {
          sendMsg: function () {
           this.$emit('childMsg', '值来自---子组件值')
          }
        }

    App.vue

    在父组件中 使用该别名(作为事件名使用),调用方法 childEvent 返回子组件传过来的值

     <p>{{message}}</p>  
        <!--<router-view></router-view>-->
     <parentTochild :sex="sexVal" @childMsg = "childEvent"></parentTochild>
    data: function () {
          return {
            sexVal: "女",
            message: ''
    
          }
        },
        methods: {
          childEvent: function (msg) {
             this.message = msg;   //  msg 来自子组件
          }
        }

     点击 “按钮”值会传到 父组件中。 组件之间不能互相传值。






  • 相关阅读:
    solr7之solrJ的使用
    solr7.3.1在CentOS7上的安装
    nginx配置:location配置方法及实例详解
    [读书]10g/11g编程艺术深入体现结构学习笔记(持续更新...)
    liunx系统计划任务管理(at/crond调度)
    Golden Gate 概念和机制
    Oracle三大经典表连接适用情况
    Oracle索引简单介绍与示例
    Oracle RAC的日志体系
    Oracle10g RAC的简单操作
  • 原文地址:https://www.cnblogs.com/congxueda/p/7150871.html
Copyright © 2011-2022 走看看