Vue2.0中父子组件间通信

前段时间做了一个小样,用到了数据通信,因为只是小样,所以就不考虑vuex了,为了加深印象,简单的做个小结。
三个按钮是一个组件,点击按钮时,能改变父组件的状态,显示不同的数据,并且实时更新按钮的选中状态

Vue2.0中父子组件间通信_第1张图片
demo.png

首先一个,vue2.0只支持单项传递数据,在子组件中我们不能直接去改动父组件的数据,那么我们可以去通知父组件,要改动哪个数据,然后让父组件去改
所以,下面我们就用到了 $emit,在子组件中通过 $emit去触发父元素的自定义事件,并把要改的值传给父元素,然后父元素就可以去监听一个事件,去改动这个值
父组件部分代码:
父组件通过绑定数据 :desc="desc" :ratings="ratings" :select-type="selectType" :only-content="onlyContent"将数据传递给子组件,select="ratingtype_select"跟toggle="ratingtype_toggle"是自定义事件,当子组件通过 $emit触发这个事件的时候,就会去执行这个事件所绑定的函数,ratingtype_select函数有一个参数,传进来的参数就是子组件的 $emit所传过来的数据,改变选中的按钮状态之后通过needShow函数去改变父元素的评论信息部分


      
....
methods: {
        ratingtype_select(type) {
          this.selectType = type
        },
        ratingtype_toggle(onlyContent) {
          this.onlyContent = onlyContent
        },
        needShow(type, text) {
          if (this.onlyContent && !text) {
            return false
          }
          if (this.selectType === ALL) {
            return true
          } else {
            return type === this.selectType
          }
        }
      },
data() {
        return {
          ratings: [],
          showFlag: false,
          selectType: ALL,
          onlyContent: false,
          desc: {
            all: '全部',
            positive: '满意',
            negative: '不满意'
          }
        }
      }

子组件部分代码:
子元素通过props去接收父元素传来的数据,通过select和toggleContent函数去通知父元素改变数据

 
{{ desc.all }}{{ ratings.length }} {{ desc.positive }}{{ positives.length }} {{ desc.negative }}{{ negatives.length }}
只看有内容的评价
props: {
        ratings: {
          type: Array,
          default() {
            return []
          }
        },
        selectType: {
          type: Number,
          default: ALL
        },
        onlyContent: {
          type: Boolean,
          default: false
        },
        desc: {
          type: Object,
          default() {
            return {
              all: '全部',
              positive: '满意',
              negative: '不满意'
            }
          }
        }
      },
      computed: {
        positives() {
          return this.ratings.filter((rating) => {
            return rating.rateType === POSITIVE
          })
        },
        negatives() {
          return this.ratings.filter((rating) => {
            return rating.rateType === NEGATIVE
          })
        }
      },
      methods: {
        select(type, event) {
          if (!event._constructed) {
            return false
          }
          this.$emit('select', type)
        },
        toggleContent(event) {
          if (!event._constructed) {
            return false
          }
          this.$emit('toggle', !this.onlyContent)
        }
      }

你可能感兴趣的:(Vue2.0中父子组件间通信)