父组件向子组件传递数据,首先要在父组件中使用v-bind
命令将要传递的数据绑定到子组件上。
<template>
<div id="app">
<Child v-bind:item1="item1" v-bind:item2="item2"></Child>
</div>
</template>
<script>
import Child from './components/Child'
export default {
name: 'App',
components: {
Child
},
data: function () {
return {
item1: "父组件中的数据1",
item2: "父组件中的数据2"
}
}
}
</script>
父组件中完成数据绑定之后,在子组件中的 props 属性接收一下父组件传递过来的数据,要接收多少数据,就在pros属性中写多少数据。
<template>
<div class="Child">
<h1>{{ item1 }}</h1>
<h1>{{ item2 }}</h1>
</div>
</template>
<script>
export default {
name: 'Child',
// 在props属性里接收父组件传递过来的数据
props: {
item1: {
type: String,
require: true
},
item2: {
type: String,
require: true
}
}
}
</script>
<template>
<div class="app">
<!-- 点击按钮触发参数传递方法 -->
<button @click="sendMsg" type="button"></button>
</div>
</template>
<script>
export default {
data () {
return {
message: "我是子组件传递的参数",
}
},
methods:{
sendMsg(){
//ok: 是父组件指定的传数据绑定的函数,this.message:子组件给父组件传递的数据
this.$emit('ok',this.message)
}
}
}
</script>
<template>
<div class="app">
<child @ok="getMessageSon"></child>
</div>
</template>
<script>
import child from './child'
export default {
data () {
return {
messageSon: ""
}
},
components:{
child,
},
methods:{
getMessageSon(item){
this.msgFormSon = item
console.log(this.msgFormSon)
}
}
}
</script>
原文:https://www.cnblogs.com/guzhenghui/p/12172578.html