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

那年仲夏 提交于 2020-12-18 02:40:34

<!--子组件页面-->
<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>

##简单来说就是父组件在调用子组件的地方:mes=loginJson.animal 这样把值传过去,子组件props接收,子组件想更新父组件的时候在触发的地方$emit("父组件的方法名",要传的值),父组件那边在调用子组件的地方写 相同的方法名

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!