Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 778
Hax0r Avatar asked Mar 07 '23 00:03

Hax0r


1 Answers

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>
like image 112
Saurabh Mistry Avatar answered Mar 09 '23 14:03

Saurabh Mistry