父传子(props) 子调用父元素的方法($emit)
代码如下: 其中@mes是子组件中在$emit中定义的名称
父组件
<template>
<div id="app" >
我是vue项目
<hello-world :data="msg" @mes="reception"></hello-world>
{{Information}}
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
data(){
return {
msg:{
name:'ly',
age:'20'
},
Information:'初始显示信息'
}
},
created() {
this.Get()
},
mounted() {
},
methods:{
Get(){
return this.msg.age=parseInt(Math.random() * 100);
},
reception(val){
console.log(val)
this.Information=val
}
}
}
</script>
<style>
</style>
子组件
<template>
<div>
<input v-model="data.name">
<input v-model="data.age">
<button @click="send('来自孩子的信息')">发送</button>
</div>
</template>
<script>
export default {
name: 'second',
props: {
data: {
name: String,
age: Number,
}
},
comments: {},
data() {
return {
message:'我是子向父传递的信息'
}
},
methods: {
send(name) {
console.log(name)
this.$emit('mes', this.message)
}
}
}
</script>
<style>
</style>