1.父组件向子组件传值:通过props数组:
先定义一个子组件,在组件中注册props
<template>
<div>
<div>{{msgFather}}(子组件)</div>
</div>
</template>
<script>
name: 'hello',
data () {
return {
}
},
props:['msgFather']
</script>
<style>
</style>
在父组件中,引入子组件,并传入子组件内需要的值
<template>
<div>
<div>父组件</div>
<child :msgFather="parentMsg"></child>
</div>
</template>
<script>
import child from './child' //引入child组件
export default {
data() {
return {
parentMsg: 'a message from parent' //在data中定义需要传入的值
}
},
components: {
child
}
}
</script>
<style>
</style>
这种方式只能由父向子传递,子组件不能更新父组件内的data
2.子组件向父组件传值:自定义事件,this.$emit,发送信息,在父组件中
子组件
<template>
<div class="hello">
<!-- 添加一个input输入框 添加keypress事件-->
<input type="text" v-model="inputValue" @keypress.enter="enter">
</div>
</template>
<script>
export default {
// 添加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 @sendiptVal='showChildMsg'></accept-and-refuse>
<p>{{message}}</p>
</div>
</template>
<script>
import AcceptAndRefuse from '@/components/public/AcceptAndRefuse'
export default {
data() {
return {
message:''
},
mounted(){
},
methods: {
showChildMsg(data){
this.message=data;
}
}
components:{
AcceptAndRefuse
}
}
</script>
<style>
</style>