vue 父子组件传值

vue 父子组件传值:props和$emit


<!--子组件页面-->
<template>
  <div class="hello">
    <!-- 添加一个input输入框 添加keypress事件-->
    <input type="text" v-model="inputValue" @keypress.enter="enter">
    <p>{{mes}}</p>
  </div>
</template>

<script>
export default {
  props:['mes'],

  // 添加data, 用户输入绑定到inputValue变量,从而获取用户输入
  data: function () {
    return {
      inputValue: ''  
    }
  },
  methods: {
    enter () {
      this.$emit("sendiptVal", this.inputValue) 
      //子组件发射自定义事件sendiptVal 并携带要传递给父组件的值,
      // 如果要传递给父组件很多值,这些值要作为参数依次列出 如 this.$emit('valueUp', this.inputValue, this.mesFather); 
    }
  }
}
</script>
<!--父组件页面-->
<template>
  <div>
    <p> father</p>
      <accept-and-refuse :mes=loginJson.animal  @sendiptVal='showChildMsg'></accept-and-refuse>
  </div>

</template>

<script>
import AcceptAndRefuse from '@/components/public/AcceptAndRefuse'
    
export default {
  data() {
    return {

      message:'hello message',
      loginJson:{
          "animal":"dog"
      }

  },
  mounted(){

  },
  methods: {
  components:{
    AcceptAndRefuse
      
  }
}
</script>

<style>

</style>

vue 父调用子组件的方法

用法: 子组件上定义ref="refName", 父组件的方法中用 this.$refs.refName.method 去调用子组件方法

详解: 父组件里面调用子组件的函数,父组件先把函数/方法以属性形式传给子组件;那么就需要先找到子组件对象 ,即 this.$refs.refName.

然后再进行调用,也就是 this.$refs.refName.method