如何通过单击将项目移动到另一个组件-vue.js

问题描述 投票:0回答:1

我想知道如何将我的物品->书从一个组件移动到另一个组件。我从api拿走了这本书,并在列表中显示了它们,所以我有一个ID。

<template>
<v-flex v-for="(book, index) in allBooks">
 <div>Title: {{ book.title }}</div>
 <i @click="markAsFavorite(book)" :class="{isActive: isMark}" class="fas fa-heart"></i>
</template>

//component books

<script>
  name: 'Books',
   data () {
     return {
      allBooks: [],
      isMark: false,
      favouriteBooks: []
    }
 },

  mounted() {
    axios.get("https://www.googleapis.com/books/v1/volumes?q=id:" + this.id)
        .then(response => {
            console.log(response)
            this.allBooks = response.data.items.map(item => ({...item, isMark: false}))
            console.log(this.allBooks)
        })
        .catch(error => {
            console.log(error)
        })
  },

   methods: {       
     markAsFavorite(book) {
       this.isMark = !this.isMark
       let favouriteAllBooks = this.favouriteBooks.push(book => { 
        book.id = // i dont know what?
    })
   },
  }
</script>

//component favourite

<template>
    <div class=showFavouriteBook>
      <p></p>
    </div>

</template>

我试图将这个带有标记书的ID与某些东西进行比较,然后这个带有标记书的数组显示在第二个模板favourite中。但是我不知道该怎么做。也许有人可以提示我一些事情?

javascript vue.js
1个回答
0
投票

您应该为此使用全局eventBus。 “ eventBus”是Vue的另一个实例,用于通过绑定到主应用程序的组件传递数据。

在应用程序的根脚本中,添加以下内容:

const eventBus = new Vue({
    data: function() {
        return {
            some_var: null,
        }
    }
});

您可以使用Vue mixin使事件总线轻松地在全球范围内访问:

Vue.mixin({
    data: function() {
        return {
            eventBus: eventBus,
        }
    }
});

现在,当您想在组件之间传递数据时,可以使用总线:

组件1

// for the sake of demo I'll use mounted method, which is invoked each time component is mounted
<script>
    export default {
        mounted: function() {
            this.eventBus.some_var = 'it works!'
        }
    }
</script>

Component 2

<template>
    <div>
        {{ eventBus.some_var }} <!-- it works -->
    </div>
</template>

此外,您可以使用$emit and $on

组件1

// for the sake of demo I'll use mounted method, which is invoked each time component is mounted
<script>
    export default {
        mounted: function() {
            // emit 'emittedVarValue' event with parameter 'it works'
            this.eventBus.$emit('emittedVarValue', 'it works!')
        }
    }
</script>

Component 2

<template>
    <div>
        {{ some_var }} <!-- "it works" once eventBus receives event "emittedVarValue" -->
    </div>
</template>
<script>
    export default {
        data: function() {
            return {
                some_var: null
            }
        },

        mounted: function() {
            // waiting for "emittedVarValue" event
            this.eventBus.$on('emittedVarValue', (data)=>{
                this.some_var = data;
            })
        }
    }
</script>

希望此答案对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.