vue组件传值

父子组件传值

首先说一下父子组件的定义,因为以前不傻傻分不清,走了很多弯路,A组件调用了B组件,A组件就是B的父组件,B组件是A的子组件。

父组件给子组件传值

父组件在调用子组件的地方采用V-bind绑定值,子组件中采用Props进行接收

具体上代码如下:

//父组件
<template>
   <div id="app">
        <img alt="Vue logo" src="./assets/logo.png">
        <p>我是父组件,我给子组件传消息</p>
        <child v-bind:msg="msg" @toparent='getMag'></child>
        <p>子组件传给我的值是:{{ msg2 }}</p></div>
</template>
<script>
  import child from '@/components/child'

  export default {
  name: 'App',
  components: {
      //HelloWorld
      child
  },
  data: function () {
      return {
          msg: '我是父组件,我给你发消息',
          msg2: ''
      }
  },
  methods: {
      getMag(msg) {
          this.msg2 = msg
      }
  }

}
</script>

···

子组件
<template>
   <div class="child">
    <p>我是一个子组件</p>
    <p>我接收到的父组件的消息是:{{msg}}</p>
    <button @click="toparent">给父组件发消息</button>
    <p>我要发送给父组件的值是:{{ toParent }}</p>
   </div>
</template>

<script>
  export default {
    name: 'child',
    props: ['msg'],
    data() {
        return {
            toParent: 'hi,我是子组件'
        }
    },
    methods: {
        toparent() {
            this.$emit('toparent', this.toParent)
        }
    }

}
</script>

<style lang="" scoped>
</style>
子组件给父组件传值

自组件采用$emit给父组件传值,具体见下图:

//父组件
<template>
   <div id="app">
        //父组件此处绑定的方法名(toparent)必须与子组件中mehods中$emit所在方法名相同,
        <child @toparent='getMag'></child>
      //父组件中定义好接收值的data,并在绑定的方法(getMag(value)value为传过来的值)中接收值
        <p>子组件传给我的值是:{{ msg2 }}</p></div>
</template>
<script>
  import child from '@/components/child'

  export default {
  name: 'App',
  components: {
      child
  },
  data: function () {
      return {
          msg2: ''
      }
  },
  methods: {
      getMag(msg) {
          this.msg2 = msg
      }
  }

}
</script>

子组件

子组件
<template>
   <div class="child">
    <p>我是一个子组件</p>
    <button @click="toparent">给父组件发消息</button>
    <p>我要发送给父组件的值是:{{ toParent }}</p>
   </div>
</template>

<script>
  export default {
    name: 'child',
    props: ['msg'],
    data() {
        return {
            toParent: 'hi,我是子组件'
        }
    },
    methods: {
//父组件调用时绑定的方法名称应该与此处的方法名一样
        toparent() {
            this.$emit('toparent', this.toParent)
        }
    }

}
</script>

<style lang="" scoped>
</style>

···

image.png

小白一枚,只为记录,若有侵权请联系。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。