javascript - Problem mit dynamisch hinzugefügten Attributfehlern von Vue.set
PHPz
PHPz 2017-05-19 10:11:05
0
2
603

Probleme, auf die Anfänger bei der Entwicklung kleiner Demos in vue2 stoßen:

<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) fügt dynamisch Attribute hinzu, aber <p class="decrease btn"> wird nicht angezeigt. Warum? Wie sollen wir es lösen?
Vue.set( Objekt, Schlüssel, Wert)

PHPz
PHPz

学习是最好的投资!

Antworte allen(2)
曾经蜡笔没有小新
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 ++
 }

小葫芦

props应该是不可变的。
data状态才是可变的。
而且Vue.set动态设置对象的属性,这个对象也应该存在于data中。

{
   data() {
     return {
         food: { } 
     }
   },

   methods: {
     increase() {
       Vue.set(this.food, 'count', 1);
     },
   },
 }
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!