Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add methods or data on current Vue instance?

I'm new to Vue.js and I'm messing around with it. Is there a way to create reusable methods and data?

Here's the very simple code I want to achieve:

page1.html

<div id="app">
  <button type="button" v-on="click: foo()">Foo</button> 
  <button type="button" v-on="click: bar()">Bar</button>
</div>

<script src="reusable.js"></script> 
<script src="page1.js"></script>  <-- Custom script -->

page2.html

<div id="app">
  <button type="button" v-on="click: foo()">Foo</button> 
  <button type="button" v-on="click: baz()">Baz</button>
</div>

<script src="reusable.js"></script> 
<script src="page2.js"></script>  <-- Custom script -->

reusable.js

var vm = new Vue({
  el: '#app',
  data: {
    name: 'John'
  },
  methods: {
    foo: function(){
      console.log('foo');
    }
  }
});

Now I'd like to access the data or add methods on my reusable.js's VM, so I can access it on my page1.js or page2.js. I have no idea how to do it, but I want to achieve something like this:

page1.js

// adds a new method on my reusable.js's vm
vm.extend({
  methods: {
    bar: function(){
      // triggers when I click the bar button
      console.log('bar'); 
      console.log(this.name); // John
    }
  }
});

page2.js

// adds a new method on my reusable.js's vm
vm.extend({
  methods: {
    baz: function(){
      // triggers when I click the baz button
      console.log('baz');
      console.log(this.name); // John
    }
  }
});

I'm aware that vm.extend is wrong (I just give you guys an idea of what I'm trying to achieve).

Do you have any suggestions?

like image 334
Chris Landeza Avatar asked Sep 24 '15 02:09

Chris Landeza


1 Answers

Perhaps you can use mixins? Pretty much like this:

var mix = {
    methods : {
        bar : function() {
            console.log('bar')
        }
    }
};

var demo = new Vue({
    el: '#demo',
    mixins : [mix],
    methods : {
        foo: function() {
            console.log('foo')
        }
    }
});

Demo: http://jsfiddle.net/dewey92/yMv7y/965/

Source: http://vuejs.org/guide/extending.html

So in your case:

Page1.html:

<div id="app">
    <button type="button" v-on="click: foo()">Foo</button> 
    <button type="button" v-on="click: bar()">Bar</button>
</div>

<script src="page1.js"></script>  <-- Custom script (or page2.js) -->
<script src="reusable.js"></script> 

page1.js:

var mix = {
    methods : {
        bar : function() {
            console.log('bar')
        }
    }
};

page2.js:

var mix = {
    methods : {
        baz : function() {
            console.log('baz')
        }
    }
};

reusable.js:

var vm = new Vue({
        el: '#app',
        mixins: [mix],
        data: {
            name: 'John'
        }
        methods: {
            foo: function(){
                console.log('foo');
            }
        }
    });
like image 63
Jihad Waspada Avatar answered Oct 16 '22 01:10

Jihad Waspada