• 【测试开发】vue父子组件之间传值


    一、父组件往子组件传值

    父组件:

    父组件中,子组件标签标定一个msg,并赋值

    <template>
    <div>
        <h1>父组件</h1>
        <m-child :msg="msg"></m-child>
    </div>
    </template>
    
    <script>
    import MChild from './Child'
    export default {
      name: "Parent",
      components:{
        MChild
      },
    }
    </script>
    
    <style scoped>
    
    </style>

    子组件:

    子组件js中加入props,并定义msg的类型

    <template>
        <div>
            <h1>子组件</h1>
            <h5>{{msg}}</h5>
        </div>
    </template>
    
    <script>
    export default {
      name: "Child",
      props:{
        msg:{
          type:String,
          default:''
        }
      },
    }
    </script>
    
    <style scoped>
    
    </style>

    效果:子组件下面有了从父组件传过来的'from parent msg'

    二、子组件往父组件传值

    子传父,一般是通过事件触发,子组件绑定一个button,点击后传值到父组件

    子组件:

    <template>
        <div>
            <h1>子组件</h1>
            <h5>{{msg}}</h5>
            <button @click="passMsg">子传父</button>
        </div>
    </template>
    
    <script>
    export default {
      name: "Child",
      props:{
        msg:{
          type:String,
          default:''
        }
      },
      methods:{
        passMsg(){
          this.$emit(('showMsg'),'i am from Child')#第一个入参为父组件中显示子组件传过来的值的方法名,第二个入参为子组件传给父组件的值
        }
      }
    }
    </script>
    
    <style scoped>
    
    </style>

    父组件:

    <template>
    <div>
        <h1>父组件</h1>
        <h3>{{msg}}</h3>
        <m-child :msg="'from Parent msg'" @showMsg="showMsg"></m-child> #子组件标签上绑定一个事件,事件可以更改msg的值显示到页面上
    </div>
    </template>
    
    <script>
    import MChild from './Child'
    export default {
      data(){
        return {
          msg:''
        }
      },
      name: "Parent",
      components:{
        MChild
      },
      methods:{
        showMsg(val){
          this.msg=val
        }
      }
    }
    </script>
    
    <style scoped>
    
    </style>

    效果

    点击前:

    点击后:

  • 相关阅读:
    事物的五种传播机制与七种传播行为
    Spring jdbcTemplate
    SpriingMVC执行流程结构
    SpringMVC视图解析器
    promise的基本使用和理解
    集合set的类型转换
    数据结构小结一
    Dotween的一些常用方法记录
    线程与进程的解释
    反射和特性
  • 原文地址:https://www.cnblogs.com/fengzx120/p/12855798.html
Copyright © 2020-2023  润新知