vue父子组件间传参

1.父传子

//子组件
<template> <div> 子组件: <span>{{inputName}}</span> </div> </template> <script> export default { // 接受父组件的值 props: { inputName: String, required: true,
     onlyContent: {
      type: Boolean,
      default: false
     }
    }
  }
</script>


//父组件

 <template>
 <div>
 父组件:
 <input type="text" v-model="name">
 <br>
 <br>
 <!-- 引入子组件 -->
 <child :inputName="name"></child>
 </div>
 </template>
 <script>
 import child from './child'
 export default {
 components: {
 child
 },
 data () {
 return {
 name: '传到子组件的值'
 }
 }
 }
 </script>

2.子组件向父组件传值(通过点击事件)

<template>
  <div>
    子组件:
    <span>{{childValue}}</span>
    <!-- 定义一个子组件传值的方法 -->
    <input type="button" value="点击触发" @click="childClick">
  </div>
</template>
<script>
  export default {
    data () {
      return {
        childValue: '我是子组件的数据'
      }
    },
    methods: {
      childClick () {
        // childByValue是在父组件on监听的方法
        // 第二个参数this.childValue是需要传的值
        this.$emit('childByValue', this.childValue)
      }
    }
  }
</script>



2.父组件

<template>
<div>
父组件:
<span>{{name}}</span>
<br>
<br>
<!-- 引入子组件 定义一个on的方法监听子组件的状态-->
<child v-on:childByValue="childByValue"></child>
</div>
</template>
<script>
import child from './child'
export default {
components: {
child
},
data () {
return {
name: ''
}
},
methods: {
childByValue: function (childValue) {
// childValue就是子组件传过来的值

  console.log(childValue);
this.name = childValue
}
}
}
</script>

参考:https://blog.csdn.net/lander_xiong/article/details/79018737

猜你喜欢

转载自www.cnblogs.com/ygyy/p/10308745.html