简体   繁体   中英

Vue: Component :prop=“object[key]” aren't reactive

I'm trying to bind a value from an Object into the prop of a Component, but it isn't reactive. I'm even using $this.set , but it doesn't work at all. Here's my template:

<div class="grid">
  <emoji-card v-for="name in shuffledEmoji"
    :name="name" :ticked="tickedEmoji[name]" :key="name"      
    @click="tickEmoji(name)"
  />
</div>
  • shuffledEmoji : Array<String>

Here, tickedEmoji is an Object with keys being strings, and values being Boolean s. tickEmoji just sets tickedEmoji[name] for that name to be true :

  methods: {
    tickEmoji (name) {
      this.$set(this.tickedEmoji, name, true)
    }
  },

That method gets called fine, but the Component doesn't notice the changes.

Child component:

<template>
  <div class="card" @click="$emit('click')">
    <img draggable="false" :src="`/static/blobs/${name}.png`">
    <img v-show="ticked" class="green-tick" draggable="false"
      src="/static/ui/green_tick.png">
  </div>
</template>

<script>
export default {
  name: 'emoji-card',
  props: ['name', 'ticked']
}
</script>

What am I doing wrong here? The child component never gets updated whenever tickEmoji is called.

For some reason, removing this initialization code in my beforeCreate fixed it. If someone could provide some insight on why this is the case, I would greatly appreciate it.

  async beforeCreate () {
    let {blobs} = await (await fetch('http://localhost:3000/api/blobs')).json()

    // init tickedEmoji map (fixes code when this loop is removed)
    for (let key of blobs) {
      this.tickedEmoji[key] = false
    }

    this.emoji = blobs
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM