【问题标题】:How do i make the Total Visible using Vue.js?如何使用 Vue.js 使总可见?
【发布时间】:2021-09-18 13:27:14
【问题描述】:

卡住了购物车,无法将我的商品价格加在一起。 我不确定我做错了什么。我在我的 vue 对象中创建了一个函数,如果将其添加到购物车中,它会将总数加在一起,但要么我调用它错误,要么函数错误。目前我在 json 文件中有一个数据数组的副本,它没有链接,因为我直接从 vue 对象中提取,但我更感兴趣的是让购物车在这个阶段添加价格

<div id="gallery">
            <div id="cart">
              <div class="card-body">
                <h6 class = "fw-light">Your Shopping Cart</h6>
                <ul class="list-group list-group-flush">
                                              <!-- Change this line to add from cart.json -->
                  <li class="list-group-item" v-for="(item, i) in cart" :key="i">
                    <div class="card" style="width: 18rem;">
                      <b>{{item.name}}</b>
                      <b>R{{item.price}}</b>
                      <img :src="item.image" width="120px" height="auto">
                      <button @click="deleteItem(i)" >Remove Item</button>
                      
                    </div>
                  </li>
                </ul>
              </div>

我如何在这里调用我的 Vue 对象的总函数?

<p>Your Total:</p>
          <h3 id ="tot">R </h3>
          <button @click="checkout()" class = "btn btn-primary">Checkout</button>
        </div>

我的 Vue 对象如下所示:

<script src = "https://unpkg.com/vue"></script>
    <script>
    let galleryItems = new Vue({
        el: '#gallery', 
        data: {
          items: [{
              id : 1,
              name : 'Double King Sized Bed', 
              image : 'images/beds/bigWhiteBed.jpg',
              price : 20000, 
              description : 'A double king sized bed with a white interior and a black cover'
            },
            {
              id : 2, 
              name : 'Queen Sized Bed with Storage Drawers', 
              image : 'images/beds/darkDrawerBed.jpg', 
              price : 15000, 
              description : 'A queen sized bed with a dark storage drawer'
            },
            {
              id : 3, 
              name : 'King Sized Bed', 
              image : 'images/beds/fancyBed.jpg', 
              price : 12000, 
              description : 'A king sized bed with a white interior and a black cover'
            },
            {
              id : 4, 
              name : 'Pine King', 
              image : 'images/beds/fancyPineBed.jpg', 
              price : 8000, 
              description : 'A twin sized bed with a white interior and a black cover'
            },
            {
              id : 5, 
              name : 'Queen Sized Bed', 
              image : 'images/beds/royalBed.jpg', 
              price : 15000, 
              description : 'A queen sized bed with a white interior and a black cover'
            },
            {
              id : 6, 
              name : 'Glass coffee table', 
              image : 'images/coffee/glassCoffeeTable.jpg', 
              price : 3000, 
              description : 'Stylish Glass Coffee table'},
            {
              id : 7, 
              name : 'Wooden coffee table', 
              image : 'images/coffee/whiteCoffeeTable.jpg', 
              price : 2000, 
              description : 'White Coffee table'},
            {
              id : 8, 
              name : 'Wooden Coffee Table on wheels', 
              image : 'images/coffee/whitewheelCoffeeTable.jpg', 
              price : 3000, 
              description : 'Easy To Move coffee table'},
            {
              id : 9, 
              name : 'Two Piece Coffee table set', 
              image : 'images/coffee/yellowCoffeeTableSet.jpg', 
              price : 2000, 
              description : 'Two tables One Price'},
            {
              id : 10, 
              name : 'Large Black Leather L-Shaped home Cinema Couch', 
              image : 'images/couches/blackLshape.jpg', 
              price : 30000, 
              description : 'Stylish Black Leather L-Shaped home Cinema Couch '},
            {
              id : 11, 
              name : 'White Leather reading Lounger', 
              image : 'images/couches/fancyChair.jpg', 
              price : 30000, description : 'Single seated Reading chair'},
            {
              id : 12, 
              name : 'Black and white Home office desk', 
              image : 'images/desks/blackAndWhiteDesk.jpg', 
              price : 2000, 
              description : 'A Stylish Work Station'},
            {
              id : 13, 
              name : 'Large L-Shaped Work Station', 
              image : 'images/desks/LshapeOffice.jpg', 
              price : 4000, 
              description : 'A spacious Corner Unit Desk'},
            {
              id : 14, 
              name : 'Combined Leisure and Home Office Station', 
              image : 'images/desks/officeBed.jpg', 
              price : 13000, 
              description : 'Combine work, relaxation and Play'},
            {
              id : 15, 
              name : 'Truss Table styled desks', 
              image : 'images/desks/trussTableOfficeDesk.jpg', 
              price : 1500, 
              description : 'Easy to assemble and move'},
            {
              id : 16, 
              name : 'Jet Black Chair', 
              image : 'images/misc/blackChair.jpg', 
              price : 1000, 
              description : 'A chair for any Environment'},
            {
              id : 17, 
              name : 'Dinning Room Table', 
              image : 'images/misc/whiteDiningRoomTable.jpg', 
              price : 10000, description : 'Dining Room Table for the family'}
          ],
          cart : []
        },
              
        methods: {
          add2cart(item){
            this.cart.push(item);
          },
          deleteItem(index){
            this.cart.splice(index, 1); 
        },
        // add a total for items in cart
        total(){
          let total = 0;
          for(let i = 0; i < this.cart.length; i++){
            total += this.cart[i].price;
          }
          return total;
        }
    } });
    document.getElementById('tot').innerHTML = galleryItems.total();
    </script>

目前它每次都显示为 0,当商品进入购物车时,我无法让它加起来价格。 这方面的极限新秀。

【问题讨论】:

    标签: javascript html vue.js cart


    【解决方案1】:

    您可以使用computed 属性而不是method 来计算total

    data: {},
    computed: {
        total() {
            let total = 0;
            for (let i = 0; i < this.cart.length; i++){
                total += this.cart[i].price;
            }
            return total;
        }
    },
    methods: {}
    

    然后你可以在你的模板部分使用{{ total }}

    <p>Your Total:</p>
        <h3 id ="tot">{{ total }}</h3>
        <button @click="checkout()" class = "btn btn-primary">Checkout</button>
    </div>
    

    计算的简单定义:

    计算属性用于以声明方式描述一个值 取决于其他值。当您将数据绑定到计算属性时 在模板内部,Vue 知道什么时候更新 DOM 计算属性所依赖的值已更改。

    在您的代码中,每当this.cart 更改(例如通过添加或删除项目)时,total 的值都会重新计算。所以你的总数总是与你的购物车同步,一切都是由 vue 自己完成的。

    您可以在此处阅读有关计算的更多信息:Computed Properties and Watchers

    【讨论】:

      【解决方案2】:

      发生这种情况是因为 Vue.js 方法不是响应式的,因此它们仅在调用时执行,而不是在参数或变量更改时执行。

      我认为computed properties 可能适合您的需求。

      它们类似于data,但让您定义一个函数。结果是反应式的,这意味着如果函数内的任何变量发生变化,则重新计算结果。在您的情况下,如果从购物车中添加或删除商品,则会重新计算总数。

      而不是做

      methods: {
        // ...
        // add a total for items in cart
        total(){
          let total = 0;
          for(let i = 0; i < this.cart.length; i++){
            total += this.cart[i].price;
          }
          return total;
        }
      }
      
      document.getElementById('tot').innerHTML = galleryItems.total();
      
      <h3 id ="tot">R </h3>
      

      您可以将方法total() 移动到计算属性

      new Vue({
        el: '#gallery', 
        data: { /* ... */ },
        computed: {
          total() {
            let total = 0;
            for(let i = 0; i < this.cart.length; i++){
              total += this.cart[i].price;
            }
            return total;
          }
        },
        methods: { /* ... */ }
      });
      
      <h3 id ="tot">{{ total }}</h3>
      

      这里,每当this.cart发生变化时,函数total()就会被调用,&lt;h3&gt;的内容也会随之更新。

      【讨论】:

        【解决方案3】:

        尝试如下 sn-p:

        new Vue({
          el: '#gallery', 
          data() {
          return {
            items: [{
                id : 1,
                name : 'Double King Sized Bed', 
                image : 'images/beds/bigWhiteBed.jpg',
                price : 20000, 
                description : 'A double king sized bed with a white interior and a black cover'
              },
              {
                id : 2, 
                name : 'Queen Sized Bed with Storage Drawers', 
                image : 'images/beds/darkDrawerBed.jpg', 
                price : 15000, 
                description : 'A queen sized bed with a dark storage drawer'
              },
              {
                id : 3, 
                name : 'King Sized Bed', 
                image : 'images/beds/fancyBed.jpg', 
                price : 12000, 
                description : 'A king sized bed with a white interior and a black cover'
              },
              {
                id : 4, 
                name : 'Pine King', 
                image : 'images/beds/fancyPineBed.jpg', 
                price : 8000, 
                description : 'A twin sized bed with a white interior and a black cover'
              },
              {
                id : 5, 
                name : 'Queen Sized Bed', 
                image : 'images/beds/royalBed.jpg', 
                price : 15000, 
                description : 'A queen sized bed with a white interior and a black cover'
              },
              {
                id : 6, 
                name : 'Glass coffee table', 
                image : 'images/coffee/glassCoffeeTable.jpg', 
                price : 3000, 
                description : 'Stylish Glass Coffee table'},
              {
                id : 7, 
                name : 'Wooden coffee table', 
                image : 'images/coffee/whiteCoffeeTable.jpg', 
                price : 2000, 
                description : 'White Coffee table'},
              {
                id : 8, 
                name : 'Wooden Coffee Table on wheels', 
                image : 'images/coffee/whitewheelCoffeeTable.jpg', 
                price : 3000, 
                description : 'Easy To Move coffee table'},
              {
                id : 9, 
                name : 'Two Piece Coffee table set', 
                image : 'images/coffee/yellowCoffeeTableSet.jpg', 
                price : 2000, 
                description : 'Two tables One Price'},
              {
                id : 10, 
                name : 'Large Black Leather L-Shaped home Cinema Couch', 
                image : 'images/couches/blackLshape.jpg', 
                price : 30000, 
                description : 'Stylish Black Leather L-Shaped home Cinema Couch '},
              {
                id : 11, 
                name : 'White Leather reading Lounger', 
                image : 'images/couches/fancyChair.jpg', 
                price : 30000, description : 'Single seated Reading chair'},
              {
                id : 12, 
                name : 'Black and white Home office desk', 
                image : 'images/desks/blackAndWhiteDesk.jpg', 
                price : 2000, 
                description : 'A Stylish Work Station'},
              {
                id : 13, 
                name : 'Large L-Shaped Work Station', 
                image : 'images/desks/LshapeOffice.jpg', 
                price : 4000, 
                description : 'A spacious Corner Unit Desk'},
              {
                id : 14, 
                name : 'Combined Leisure and Home Office Station', 
                image : 'images/desks/officeBed.jpg', 
                price : 13000, 
                description : 'Combine work, relaxation and Play'},
              {
                id : 15, 
                name : 'Truss Table styled desks', 
                image : 'images/desks/trussTableOfficeDesk.jpg', 
                price : 1500, 
                description : 'Easy to assemble and move'},
              {
                id : 16, 
                name : 'Jet Black Chair', 
                image : 'images/misc/blackChair.jpg', 
                price : 1000, 
                description : 'A chair for any Environment'},
              {
                id : 17, 
                name : 'Dinning Room Table', 
                image : 'images/misc/whiteDiningRoomTable.jpg', 
                price : 10000, description : 'Dining Room Table for the family'}
            ],
            cart : [{
                id : 1,
                name : 'Double King Sized Bed', 
                image : 'images/beds/bigWhiteBed.jpg',
                price : 20000, 
                description : 'A double king sized bed with a white interior and a black cover'
              },
              {
                id : 2, 
                name : 'Queen Sized Bed with Storage Drawers', 
                image : 'images/beds/darkDrawerBed.jpg', 
                price : 15000, 
                description : 'A queen sized bed with a dark storage drawer'
              },],
            }
          },
          computed: {
            total() {
              return this.cart.reduce((acc, c ) => acc += c.price, 0) 
            }
          },
          methods: {
            add2cart(item){
              this.cart.push(item);
            },
            deleteItem(index){
              this.cart.splice(index, 1); 
          },
        } 
        });
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
        <div id="gallery">
          <div id="cart" style="display: flex;">
            <div class="card-body">
              <h6 class = "fw-light">Your Shopping Cart</h6>
              <ul class="list-group list-group-flush">
                <li class="list-group-item" v-for="(item, i) in cart" :key="i">
                  <div class="card" style="width: 18rem;">
                    <b>{{item.name}}</b>
                    <b>R{{item.price}}</b>
                  <!--<img :src="item.image" width="50px" height="auto">-->
                    <button @click="deleteItem(i)" >Remove Item</button>
                  </div>
                </li>
              </ul> 
            </div>
            <div>
              <p>Your Total:</p>
              <h3 id ="tot">{{total}}</h3>
              <button @click="checkout()" class = "btn btn-primary">Checkout</button>
            </div>
          </div>
        </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-05
          • 1970-01-01
          • 2021-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多