在Vue中,因其单向数据流的原理,我们父组件传递的值是不能给子组件修改的。但是如果没有用Vuex/eventBus等,我们就会出现根据原生Vue的方法来让子组件修改父组件传递的值(Props)的需求。如果我们直接让子组件修改父组件的值是会报错的,这在vue中是不被允许的。

1. 使用 v-model/双向绑定

写法如下:

1.1 父组件

  1. <template>
  2. <div>
  3. <children v-model="demo"></children>
  4. </div>
  5. </template>

1.2 子组件

  1. <template>
  2. <div>
  3. <div>{{demoData}}</div>
  4. <button @click="setData">修改数据</button>
  5. </div>
  6. </template>
  7. export default{
  8. props:{
  9. demo:{
  10. type:boolean,
  11. default:''
  12. }
  13. },
  14. data(){
  15. return {
  16. demoData:this.demo
  17. }
  18. },
  19. methods:{
  20. setData(){
  21. this.demoData = !this.demoData
  22. this.$emit('input',this.demoData)
  23. }
  24. }
  25. }