2

I have the following vuejs component. I know that it is a pretty simple example, but still it does not load correctly. Find below my code:

Vue.component('my-component', {
  template: '<div>{{ msg }}</div>',
  data: {
    msg: 'hello'
  }
});

new Vue({
  el: '#app-6'
});
<!DOCTYPE html>
<html lang="en">
<meta>
<meta charset="UTF-8">
<title>Components in Vue.js</title>
</meta>

<body>

  <div id="app-6">
    test
    <my-component></my-component>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script>
</body>

</html>

Any suggestions what I am doing wrong?

I appreciate your replies!

2
  • 1
    Define "does not load correctly", are you getting error messages? Commented Jan 23, 2018 at 7:15
  • 1
    Data must be a function always. Commented Jan 23, 2018 at 7:23

3 Answers 3

4

Data Must be a function always

var data={msg: 'hello'}    
Vue.component('my-component', {
  template: '<div>{{ msg }}</div>',
  data:function() {
       return data;
  }
});

new Vue({
  el: '#app-6'
});
<!DOCTYPE html>
<html lang="en">
<meta>
<meta charset="UTF-8">
<title>Components in Vue.js</title>
</meta>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script>
  <div id="app-6">
    test
    <my-component></my-component>
  </div>


</body>

</html>

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

Comments

2

Your data should be a function like this:

data () {
    return {
        msg: 'Hello'
    }
}

More information here: https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

Comments

1

you should do it like this.

Vue.component('my-component', {
  template: '<div>{{ msg }}</div>',
   data: function () {
    return {
      msg: 'Hello'
   }
}
});

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.