4

I am new to vue.js. and i am using 2.5.13 version.

I'm trying to access my data variable in component file script. But this give to me a undefined message.

Id attribute in the component returns correct value, but inside script, it would return undefined.

If I want to use that variable, what do I need to do?

Below is my app.js code

import App from './components/App.vue';
new Vue(Vue.util.extend({
        router,
        data : {
            test : 1
        },
    }, App))
        .$mount('#root');

And bleow is my App component code

<template>
    <div id="app" :data-id="test">

    </div>
</template>
<script>
    console.log(this.data);
</script>
2
  • 2
    The code looks strange for me not sure where to start. I suggest you to learn basic VueJS from this free course laracasts.com/series/learn-vue-2-step-by-step. An hour of taking this course would give you enough idea to start with VueJS in the proper manner. :) Commented Feb 1, 2018 at 7:44
  • thanks ! spicydog ^^ Commented Feb 1, 2018 at 8:06

1 Answer 1

7

assign variable var app = new Vue({..}) to your Vue App. and access variable outside vue app by using appname.variable_name like app.message

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})


console.log(app.message);
<script src="https://cdn.jsdelivr.net/npm/vue"></script>


<div id="app">
  {{ message }}
</div>

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

1 Comment

but what about the reactivity of Vue JS?

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.