Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

vue.js - The global variable is not working with VueJS & Laravel

I have a global variable in app.blade.php like this>

<script>
window.App = {!! json_encode([
    'apiToken' => Auth::user()->api_token,
]) !!};
</script>

I have in app.blade.php layouts a

and it has:

 <script>
  export default {
    created() {
        this.getRol();
    },
    methods: {
        getRol() {
            console.log(App.apiToken);
            axios.get('/api/user?api_token='+App.apiToken)
            .then(response => {
                console.log(response);
                this.rol_id = response.data.data.rol_id;
            });
        }
    }
  }
  </script>

But I wonder why does it say this error?

[Vue warn]: Error in created hook: "ReferenceError: App is not defined"

And it's created globally.

Thanks

question from:https://stackoverflow.com/questions/66050935/the-global-variable-is-not-working-with-vuejs-laravel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To create a "global variable" to be used in Vue, see LinusBorg's answer on the Vue forums here: https://forum.vuejs.org/t/global-variable-for-vue-project/32510/4

Contents of the post:

It’s not a good idea to use tru global variables in projects, to keep the global namespace clean.

Instead, create a small file, from where you can export any variable that you need to use in many places:

// variables.js
export const myVar = 'This is my variable'
export const settings = {
  some: 'Settings'
}
// in your Vue
import { myVar, Settings } from './variables.js'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...