父传子:
<body>
<div id='app'>
<songname title="我是父组件传来的"> </songname>
<songname></songname>
<songname :title="title"></songname>
</div>
<template id="login">
<div>
登录组件
父组件传值:{{title}}
</div>
</template>
<script>
// 定义组件
Vue.component("songname", { //组件名
template: "#login", //组件id
props: {
// 1、 指定数据类型 title:string
// 2、指定多种数据类型
// title: [String, Number],
// 3.指定默认数据
title: {
type: String,
default: "课程标题",
},
}
})
</script>
<script>
const vm = new Vue({
el: '#app',
data: {
title: "我是父组件传来的动态属性绑定"
}
})
</script>
子传父:
<body>
<!-- 父 -->
<div id='app'>
<!-- 子 -->
<sonname @father="fatherchange"></sonname>
{{sondata}}
</div>
<template id="login">
<div>
登录组件
父组件传值:{{title}}
<button @click="addDataTofather"> 点我干大事</button>
</div>
</template>
<script>
Vue.component("sonname", {
template: "#login",
props: {
// 1.指定数据类型
// title:String
// 2指定多种数据类型
// title:[String,Number]
// 3指定默认数据
// title:{
// type:String,
// default:"课程标题"
// },
title: {
type: [String, Number],
default: "课程标题"
}
},
methods: {
addDataTofather() {
this.$emit("father", "传过来的子组件数据")
}
},
})
</script>
<script>
const vm = new Vue({
el: '#app',
data: {
title: "俺是父组件传来的动态属性绑定",
sondata: ""
},
methods: {
fatherchange(data) {
console.log(data);
this.sondata = data
}
},
})
</script>