3

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)
        }
      }

2 Answers 2

11

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Why this isn't the accepted answer? It's the simplest and easiest method.
10

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
      }
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.