一、父组件向子组件传递数据(props)
1.parent
<template>
<view>
<child :parentData="parentData"></child>
</view>
</template>
<script>
import child from "@/components/example/child.vue"
export default {
components: {
child: child
},
data() {
return {
parentData: '我是父组件中的数据',
}
}
}
</script>
<style>
</style>
2.child
<template>
<view>
<text>{
{
parentData}}</text>
</view>
</template>
<script>
export default{
data(){
return{
}
},
props:{
parentData:{
type:String,
default:null
}
}
}
</script>
<style>
</style>
二、子组件向父组件传递数据(emit)
1.parent
<template>
<view>
<child :parentData="parentData" @changes="childClick" ></child>
<br>
<text>{
{
childData}}</text>
</view>
</template>
<script>
import child from "@/components/example/child.vue"
export default {
components: {
child: child
},
data() {
return {
parentData: '我是父组件中的数据',
childData:''
}
},
methods:{
// 子组件向父组件传值
childClick(e) {
console.log(e)
this.childData = e;
}
}
}
</script>
<style>
</style>
2.child
<template>
<view>
<text>{
{
parentData}}</text>
<br>
<view style="width: 100%;">
<input class="uni-input" focus="true" type="text" value="search" v-model="search" placeholder="请输入传入父组件的值" placeholder-class="color:#4a4a4a"/>
<button type="primary" @click="childClick">传递信息</button>
</view>
</view>
</template>
<script>
export default{
data(){
return{
search:''
}
},
props:{
parentData:{
type:String,
default:null
}
},
methods:{
childClick(){
console.log(this.search);
this.$emit('changes',this.search)
}
}
}
</script>
<style>
</style>
三、子组件与父组件数据同步(.sync)
1.parent
<template>
<view>
<child :syncData.sync="syncData" ></child>
<view class="parent" style="background: #09BB07;">
<input :value="syncData" v-model="syncData" placeholder="请输入值" style="background: #C0C0C0;" />
<view>sync同步(parent):{
{
syncData}}</view>
</view>
</view>
</template>
<script>
import child from "@/components/example/child.vue"
export default {
components: {
child: child
},
data() {
return {
syncData: ''
}
},
methods:{
}
}
</script>
<style>
</style>
2.child
<template>
<view>
<view>
sync数据同步(child):{
{
syncData}}
</view>
</view>
</template>
<script>
export default{
data(){
return{
}
},
props:{
syncData:{
type:String,
default:null
}
}
}
</script>
<style>
</style>