美文网首页
vue父子组件传值(属性计算)实例

vue父子组件传值(属性计算)实例

作者: 已不淘气很多年 | 来源:发表于2018-05-03 10:32 被阅读0次

最近在使用ionic开发app时(基于Angular4),做到了购物车功能,涉及到每个门店下都有各自的订单,然后每个订单下有多个商品,可以修改数量,价格和总价格及时变更。于是联想起vue,又使用vue实现了一个类似功能,父子组件传值以及属性计算的demo。

先上功能图:

image.png

demo的功能点是:每件商品做成了一个组件,组件包含商品的名称,单价,数量,以及总价格。
然后在父组件做了引用商品子组件,呈现商品列表,子组件数据变化时,并且及时从子组件传回单件商品总价。

商品子组件:Product.vue

<template>
  <div class="hello">
    <h2>{{ productName }}</h2>
    <div>单价: <input type="text" v-model="price"></div>
    <div>数量: <input type="text" v-model="number"></div>
    <div>总价格:{{ total }}</div>
  </div>
</template>
<script>
export default {
  name: 'Product',
  data () {
    return {
      price: 0,
      number: 0
    }
  },
  props: ['index', 'productName'],
  updated () {
    this.setProduct()
  },
  methods: {
    setProduct () {
      this.$emit('getProduct', {index: this.index, total: this.total})
    }
  },
  computed: {
    total () {
      return this.price * this.number
    }
  }
}
</script>

购物车父组件Cart.vue

<template>
  <div class="hello">
    <h1>总金额: {{ total }}</h1>
    <product
      :productName="item.name"
      :index="index"
      :key='index'
      @getProduct="getValue"
      v-for="(item, index) in productList">
    </product>
  </div>
</template>
<script>
import Product from '@/components/Product'
export default {
  name: 'Cart',
  data () {
    return {
      productList: [
        {
          id: 1,
          sum: 0,
          name: '爱法贝鞋子'
        },
        {
          id: 2,
          sum: 0,
          name: '1001夜牛仔外套'
        }
      ]
    }
  },
  methods: {
    getValue (value) {
      this.productList[value.index].sum = value.total
    }
  },
  computed: {
    total () {
      return this.productList.reduce((accumulator, current) =>
        accumulator.sum + current.sum
      )
    }
  },
  components: {
    Product
  }
}
</script>

展示效果

image.png

这个功能比较简单:
子组件进行总价更新的时候,通过事件将对应索引的商品(或者对应商品的ID)的总价传递回来,然后父组件进行属性计算,遍历所有商品进行总价的相加,得到总金额。
涉及到了父子组件传值,属性的计算等功能,可以作为练手来熟悉这个功能。

相关文章

网友评论

      本文标题:vue父子组件传值(属性计算)实例

      本文链接:https://www.haomeiwen.com/subject/rolkrftx.html