首先父子组件传值:很简单
子组件改变父组件的方式一:
adddata: function () {
this.$emit('addnum:datanum', this.datanum)
}
通过this.$emit 的方式传递给父组件,然后在父组件中写方法,改变值。
这里有一个问题就是加上 :datanum 子组件改变不了父组件值
去掉就可以改变
<children :datanum="datan" @addnum="addnumdata"></children>
addnumdata: function () {
this.datan += 1
},
方式二 使用.sync 修饰符
首先在子页面同样使用this.$emit
adddata: function () {
this.$emit('update:datanum',this.num)
}
注意update 要写对 : 后面是父组件传的值(要改的属性),和值
父组件中:
<child :datanum.sync="datan"></child>
datan 就是要改变的父组件值
我自己觉得是.sync 可以理解为 “双向绑定”,父传子是单向数据流是绑定的,但是子传父需要一定的方式 this.$emit(‘update:***’ ,***)
:datanum.sync 其实也是向子组件传值的过程
个人理解,请大家指正
prop为对象数组时不曾尝试
父组件代码:
<template>
<div style="color: red">
<button @click="add">点击</button>
父页面---{{datan}}
父页面---{{post.title}}
父页面---{{post.num}}
<div style="padding: 20px 0">-------------------------------------------------</div>
<children :datanum="datan" @addnum="addnumdata"></children>
<child :datanum.sync="datan"></child>
</div>
</template>
<script>
import children from './children'
import child from './child'
export default {
name: "",
data: function () {
return {
msg: 'This is a Vue project',
post: {
num: 0,
title: 'My Journey with Vue'
},
datan: 1,
}
},
create: function () {
}, /*渲染前调用*/
mounted: function () {
}, /*渲染后调用*/
components: {
child,
children
},// 组件注册
methods: {
addnumdata: function () {
this.datan += 1
},
add: function () {
this.datan += 1
},
} /*方法*/
}
</script>
<style scoped>
</style>
子组件一:
<template>
<div>
<div>
<button @click="adddata()">点击</button>
子页面--{{datanum}}
子页面--{{datanum}}
</div>
<div style="padding: 20px 0">-------------------------------------------------</div>
</div>
</template>
<script>
export default {
name: "",
data: function () {
return {
msg: 'This is a Vue project'
}
},
create: function () {
}, /*渲染前调用*/
props: {
datanum: Number
},
mounted: function () {
}, /*渲染后调用*/
methods: {
adddata: function () {
this.$emit('addnum:datanum', this.datanum)
}
} /*方法*/
}
</script>
<style scoped>
</style>
子组件二:
<template>
<div>
<div>
<button @click="adddata()">点击</button>
子页面--{{datanum}}
子页面--{{datanum}}
</div>
<div style="padding: 20px 0">-------------------------------------------------</div>
</div>
</template>
<script>
export default {
name: "",
data: function () {
return {
msg: 'This is a Vue project',
num:0
}
},
create: function () {
}, /*渲染前调用*/
props: {
datanum: Number
},
mounted: function () {
}, /*渲染后调用*/
methods: {
adddata: function () {
this.$emit('update:datanum',this.num)
}
} /*方法*/
}
</script>
<style scoped>
</style>