如何在 Vue.js 中的组件之间共享方法? [英] How can I share a method between components in Vue.js?

查看:31
本文介绍了如何在 Vue.js 中的组件之间共享方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Check out this simple shopping cart demo:

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

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

A user can pick a veggie and a fruit, and it will be added into the cart array. The function that adds a fruit/veggie is very similar, and I want to combine it into a function that can be shared across both components.

    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 Router,感谢您的帮助!

How can I make it so I can alter this method and have it used globally? I'm using the Vue Router with this project btw, thanks for any help!

推荐答案

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

I found this technique to be more simple/satisfactory, as I prefer composition over inheritance:

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 无关的测试.

This will also allow you to write Vue-agnostic tests.

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

NOTE: if you need foo to run in Vue-scope replace this.foo = shared.foo with this.foo = shared.foo.bind(this)

这篇关于如何在 Vue.js 中的组件之间共享方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆