Josh Winters
Josh Winters

Reputation: 855

function outside vue, passing data into vue

I have a function that runs outside of a vue component. I want the data it returns passed to the data in the vue component.

    <script>
      function example(){
        var item = 'item';
      };

      example();

      export default {
        data(){
          return (this is where I want item represented)
        }
      }

Upvotes: 3

Views: 6317

Answers (2)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

See Working Demo :

var app = new Vue({
  el: '#app',
  data: {
    item: "Hi"
  }
});


function example(){
      app.item='Hello How R You ?';
};
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id="app">
<button onclick="example()" >Click ME</button>
  {{ item }}
</div>

Upvotes: 11

user320487
user320487

Reputation:

Assign the function to a const and call it within one of the component lifecycle hooks:

const example = function (){
    return 'item';
};

export default {
    created () {
        this.item = example()
    },
    data(){
      return {
         item: null
      }
    }
  }

Upvotes: 10

Related Questions