如何在 Vue.js 中的组件之间共享方法?

新手上路,请多包涵

看看这个简单的购物车演示:

http://plnkr.co/edit/CHt2iNSRJAJ6OWs7xmiP?p=preview

用户可以选择蔬菜和水果,并将其添加到购物车数组中。添加水果/蔬菜的函数非常相似,我想将它组合成一个可以在两个组件之间共享的函数。

     selectFruit: function(product){
       var cart = this.cart
       for(p in cart){
       if (cart[p]["type"] == "fruit"){
           console.log("We already got a fruit!, Let's remove " + cart[p]["name"] + " and add in " + product["name"]);
              this.cart.$remove(cart[p])
             }
            }
            console.log("Adding " + product.name + " to cart.");
            var productName = product.name
            var cartFruit = {name: product.name, type: 'fruit'}
            this.cart.push(cartFruit)
}

selectVeggie: function(product){
    var cart = this.cart
    for(p in cart){
        if (cart[p]["type"] == "veggie"){
           console.log("We already got a veggie!, Let's remove " + cart[p]["name"] + " and add in " + product["name"]);
           this.cart.$remove(cart[p])
        }
    }
    console.log("Adding " + product.name + " to cart.");
    var productName = product.name
    var cartVeggie = {name: product.name, type: 'veggie'}
    this.cart.push(cartVeggie)
}

我怎样才能做到这一点,以便我可以改变这个方法并让它在全球范围内使用?顺便说一句,我在这个项目中使用了 Vue 路由器,感谢您的帮助!

原文由 Mike 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 376
1 个回答

我发现这种技术更简单/令人满意,因为我更喜欢组合而不是继承:

src/shared.js

 export default {
  foo: function() { alert("foo!") }
}

src/yourcomponent.vue

 <template>...</template>

<script>
  import shared from './shared'

  export default {
    created() {
      this.foo = shared.foo // now you can call this.foo() (in your functions/template)
    }
  }
</script>

这也将允许您编写与 Vue 无关的测试。

注意:如果您需要 foo 在 Vue 范围内运行,请将 this.foo = shared.foo 替换为 this.foo = shared.foo.bind(this)

原文由 coderofsalvation 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏