Rumah  >  Soal Jawab  >  teks badan

javascript - Masalah kegagalan atribut ditambah secara dinamik Vue.set

Masalah yang dihadapi oleh orang baru dalam vue2 membangunkan demo kecil:

<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) menambah atribut secara dinamik, tetapi <p class="decrease btn"> tidak dipaparkan. Bagaimana kita harus menyelesaikannya?
Vue.set( objek, kunci, nilai )

PHPzPHPz2689 hari yang lalu607

membalas semua(2)saya akan balas

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新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 ++
     }

    balas
    0
  • 高洛峰

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

    prop hendaklah tidak berubah.
    Keadaan data berubah-ubah.
    Dan Vue.set menetapkan sifat objek secara dinamik dan objek ini juga harus wujud dalam data.

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

    balas
    0
  • Batalbalas