父组件向子组件传值
父组件
<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>