代码之家  ›  专栏  ›  技术社区  ›  L-R

如何从另一个Vue组件强制重传器

  •  0
  • L-R  · 技术社区  · 6 年前

    我有一个购物篮,当我从一个应用程序中选择“添加到购物篮”时,我想让购物篮实时重新加载。当添加到购物篮时,我会将此项目发布到API。篮子从这个API获取并呈现篮子组件中的数据。

    我正在使用一个事件总线来告诉篮子组件一个新项目已经添加到我的 $on 两者都不起作用 $forceUpdate() 或者发出另一个提取请求,用新项重新呈现组件。

    这在我的项目组件中:

    methods: {
    submit(e){
      e.preventDefault()
      let data = this.createBasketObject(this.experience)
      fetch('http://localhost:3000/api/basket', {
        method: 'POST',
        body: JSON.stringify(data),
        headers: { 'Content-Type': 'application/json'}
      })
      .then( eventBus.$emit('basket-updated', true))
    }
    

    这是我的篮子组件:

    <template lang="html">
      <div class="">
        <h3>Basket</h3>
        <basket-item
          v-for="item in items"
          :key="item._id"
          :item="item"
        />
        <p>Total: £{{ total}}</p>
      </div>
    

    <script>
    import BasketItem from './BasketItem.vue';
    import { eventBus } from '../main.js';
    
    export default {
      name: 'basket',
      data(){
        return {
          items: [],
          total: 0
        }
      },
      components: {
        'basket-item': BasketItem
      },
      mounted(){
        fetch('http://localhost:3000/api/basket')
        .then(res => res.json())
        .then(data => this.items = data)
        .then(items => this.calcTotal(items))
    
        eventBus.$on('basket-updated', (data) => {
          if(data){
            this.$forceUpdate()
          }
        })
      }
    

    我基本上是在尝试像in react这样的设置状态,但是在刷新页面之前,这个篮子不会更新。

    在Vue中,我是否可以在不使用套接字的情况下执行此操作?

    谢谢

    1 回复  |  直到 6 年前
        1
  •  0
  •   IGionny    6 年前

    LoadBasket() {
     fetch('http://localhost:3000/api/basket')
        .then(res => res.json())
        .then(data => this.items = data)
        .then(items => this.calcTotal(items));
    }
    
    mounted(){
      //The first time:
      this.LoadBasket();
    
      eventBus.$on('basket-updated', (data) => {
          if(data){
             //on basket updated
              this.LoadBasket();
          }
        });
    }
    

    this.Items.push(newItem);
    

    https://vuex.vuejs.org/guide/state.html