search

Home  >  Q&A  >  body text

javascript - Vue.set dynamically added attribute failure problem

vue2 Problems encountered by novices developing small demos:

<template>
    <p class="cartctrl">
        <p class="decrease btn" v-show="food.count > 0">
            <span class="btn-content">-</span>
        </p>
        <p class="count" v-show="food.count > 0">{{food.count}}</p>
        <p class="increase btn" v-on:click="increaseCount">
            <span class="btn-content">+</span>
        </p>
    </p>
</template>

<script>
    import Vue from 'vue'

    export default {
        props : {
            food : {
                type : Object
            }
        },
        methods : {
            increaseCount : function () {
                if (!this.food.count) {
                    this.food.count = 1
                    Vue.set(this.food, 'count', 1)
                    console.log(this.food)  // Object {count: 1, __ob__: Observer}
                } else {
                    this.food.count ++
                }
            }
        }
    }
</script>

Vue.set(this.food, 'count', 1) dynamically adds attributes, but <p class="decrease btn"> is not displayed. What is the reason? How should we solve it?
Vue.set( object, key, value )

PHPzPHPz2753 days ago656

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:13:05

    increaseCount : function () {
      if (!this.food.count) {
        this.food.count = 1
        this.food.$set('count', 1) // 这里应该这么设置才有效
        console.log(this.food)  // Object {count: 1, __ob__: Observer}
     } else {
      this.food.count ++
     }

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:13:05

    props should be immutable.
    The data state is variable.
    And Vue.set dynamically sets the properties of the object, and this object should also exist in data.

    {
       data() {
         return {
             food: { } 
         }
       },
    
       methods: {
         increase() {
           Vue.set(this.food, 'count', 1);
         },
       },
     }

    reply
    0
  • Cancelreply