Hax0r
Hax0r

Reputation: 1803

Vue JS how to access data variable in script

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>

Upvotes: 4

Views: 23005

Answers (1)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

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>

Upvotes: 7

Related Questions