vue父子组件数据双向绑定

158 阅读1分钟
<template>
  <div>   
    <button-counter :propCount.sync="parentCount"></button-counter>
    <h1>{{parentCount}}</h1>
  </div>
</template>

<script>
import Vue from 'vue';

Vue.component('button-counter',{
    data:function(){
        return {
            childCounter:0,       
        }
    },
    created () {
        this.childCounter = this.propCount;  
    },
    props: ['propCount'],
    template:`<div><button v-on:click="handleIncrement">{{childCounter}}</button></div>`,
    methods: {
        handleIncrement(){
            this.childCounter +=1;
            this.$emit('update:propCount',this.childCounter);
        }
    }
});

export default {
  name: 'HelloWorld',
  data () {
    return {
      parentCount: 100,
    }
  },
}
</script>