一.父组件向子组件传数据
<!-- 父组件father -->
<!-- 父组件通过message属性把msg的值传给子组件child -->
<template>
<div>
<child :message="msg"></child>
</div>
</template>
<script>
import Child from './child'
export default {
name: 'father',
data () {
return {
msg: 'this is msg'
}
},
components:{
Child
}
}
</script>
<!-- 子组件child -->
<!-- 子组件通过props接收父组件传的值 -->
<template>
<div>
{{message}}
</div>
</template>
<script>
export default {
props:['message']
}
</script>
二.子组件向父组件传数据
<!-- 子组件child -->
<!-- 点击按钮传值 -->
<template>
<div>
<button @click="sendMsg">确定</button>
</div>
</template>
<script>
export default {
data() {
return {
newMsg: "msg is Changed"
};
},
methods: {
sendMsg() {
this.$emit("msgChanged", this.newMsg);
}
}
};
</script>
<!-- 父组件father -->
<template>
<div>
<child @msgChanged="showMsg"></child>
</div>
</template>
<script>
import Child from './child'
export default {
name: 'father',
components:{
Child
},
methods:{
showMsg(data){
console.log(data)
}
}
}
</script>