How can I share a method between components in Vue.js?

前端 未结 4 1493
野趣味
野趣味 2020-12-13 03:55

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 04:36

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

    src/shared.js

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

    src/yourcomponent.vue

    
    
    
    

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

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

提交回复
热议问题