Vue JS 3:如何将数据从一个组件传递到另一个组件?

2024-02-10

我正在尝试共享存储在变量中的数据favorite_count在收藏夹组件中Favorites.vue文件。我想与应用程序组件共享该数据App.vue文件,但我无法。我希望如果我改变的值favorite_count在收藏夹组件中,它在应用程序组件中发生变化。在网上做了很多研究,但还没有成功。关于我可能做错了什么有什么想法吗?

Favorites.vue file

<template>
    <div class="row m-5">
        <h3 class="col-8">Your Favorites</h3>
        <div class="col-4">
            <p class="pull-right m-1">Picks 
            <span >{{ favorite_count }}</span>  / 5</p>
        </div>
        <hr>
    </div>
</template>
<script>
export default {
    name: 'favorites',
    data() {
        return {
            favorite_count: 5,
        }
    },
    methods: {
        changeFavoriteCount() { 
            this.favorite_count = this.favorite_count + 2;
        },
        emitToParent (event) {
          this.$emit('childToParent', this.favorite_count)
        }
    }
}
</script>

App.vue file

<template>
    <div class="navbar navbar-expand-md navbar-dark bg-primary">
        <div class="collapse navbar-collapse" id="navbarResponsive">
            <ul class="navbar-nav"> 
                <li class="nav-item">
                    <router-link to="/favorites" class="btn btn-info">
                      Favorites ( {{ favorite_count }} )
                    </router-link>
                </li>
            </ul>
        </div>
    </div> 
</template>
<script> 
import Favorites from './components/Favorites.vue'
 
export default {
  name: 'App',
  components: {
    Favorites
  },
  data () {
    return { 
      favorite_count: 0, 
    }
  }
}
</script>

如果你要使用<router-view>稍后在您的申请中,我建议这个解决方案 https://stackoverflow.com/a/68217600/16315484

如果你要包括Favorites inside <template> in App.vue, 您可以使用props https://v3.vuejs.org/guide/component-props.html#prop-types:

1.在父组件 (App.vue) 中声明您的“共享”变量

data () {
  return { 
    favorite_count: 0, 
  }
},

2.在子组件中定义 props (Favorites.vue)

export default {
  props: { favorite_count: Number },
  ...
}

3. Pass favorite_count作为支撑Favorites

<template>
  ...
    <Favorites :favorite_count="favorite_count" ... />
</template>

如果您需要更新favorite_count- 向父组件发出事件。更多相关信息请参见Vue docs https://v3.vuejs.org/guide/component-custom-events.html#custom-events

Edit:只是澄清一下:如果您要更新favorite_count from 收藏夹.vue,您需要发出一个事件App.vue以避免改变道具。

这也意味着你需要移动你的changeFavoriteCount()功能为App.vue并将侦听器应用于将调用此函数的子组件:

// App.vue
<template>
  ...
    <Favorites 
       @your-update-event="changeFavoriteCount" 
       :favorite_count="favorite_count" ...
    />
</template>

...

changeFavoriteCount(newVal) { 
    this.favorite_count = newVal;
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vue JS 3:如何将数据从一个组件传递到另一个组件? 的相关文章

随机推荐