vue父子组件传值

父组件向子组件传值

父组件

<template>
  <div>
    <hello ref="good" message="gggggg"></hello>
  </div>
</template>
<script>
import hello from './ChildComponent'
export default {
  components: {
    hello
  }
}
</script>

子组件,使用prop接收父组件传来的值。

<template>
  <div>hello world</div>
</template>
<script>
export default {
  name: 'ChildComponent',
  props: ['message'],
  created () {
    console.log(this.message)
  }
}
</script>

子组件向父组件传值

父组件

<template>
  <div>
    <hello @good="show"></hello>
  </div>
</template>
<script>
import hello from './ChildComponent'
export default {
  name: 'HelloWorld',
  components: {
    hello
  },
  methods: {
    show(val) {
      alert(val)
    }
}
</script>

子组件,使用this.$emit(函数名,参数)向父组件传值。

<template>
  <div>hello world</div>
</template>
<script>
export default {
  name: 'ChildComponent',
  created () {
    this.$emit('good', 'good morning')
  }
}
</script>

子组件也可以这样

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