在Vue中,因其
单向数据流
的原理,我们父组件传递的值是不能给子组件修改的。但是如果没有用Vuex/eventBus等,我们就会出现根据原生Vue的方法来让子组件修改父组件传递的值(Props)的需求。如果我们直接让子组件修改父组件的值是会报错的,这在vue中是不被允许的。
1. 使用 v-model/双向绑定
1.1 父组件
<template>
<div>
<children v-model="demo"></children>
</div>
</template>
1.2 子组件
<template>
<div>
<div>{{demoData}}</div>
<button @click="setData">修改数据</button>
</div>
</template>
export default{
props:{
demo:{
type:boolean,
default:''
}
},
data(){
return {
demoData:this.demo
}
},
methods:{
setData(){
this.demoData = !this.demoData
this.$emit('input',this.demoData)
}
}
}