2

I've started to build vue.js app with Laravel using single-file components. The problem is with my app object: it is a DOM, not a Vue object and app won't work properly.

When I start my app, components are rendered properly, vue-devtools recognizes Vue 2.2.6, evertything seems to work in the right way.

But when I type

console.log(app)

in chrome console I see a DOM object:

<div id="app"></div>

What more, when I try to change title property (and wanted to see changed hello component on screen) just by typing

app.title = "awesomness"

in console, my component wouldn't change, but only my div#app: (typed console.log(app)

<div id="app" title="awesomness"></div>

The question is: why? Samples below.

Test component Hello.vue

<template>
    <div>
        <p>{{ greeting }} World!</p>
    </div>

<script>
    module.exports = {
        props: ['greeting'],
        data: function() {
            return {
            }
        }
    }
</script>

<style scoped>
    p {
        color: red;
        font-size: 20px;
    }
</style>

part of my index/index view from laravel:

<div id="app">
    <hello :greeting="title"></hello>
</div>

and finally my /resources/assets/js/app.js file

import Vue from 'vue'
import Hello from './components/Hello.vue'

Vue.component('hello', Hello);

var app = new Vue({
    el: '#app',
    data: {
        title: 'Hello Vue!',
        todos: [
            { text: 'task 1' },
            { text: 'task 2' },
            { text: 'task 3' },
            { text: 'task 4' }
        ],
    }
})
piotr
  • 1,282
  • 1
  • 8
  • 20

2 Answers2

5

In most browsers, the id attribute of an HTML element is exposed in the global scope as a variable. So, when you type console.log(app), it is returning the element that has the id, "app".

You've named your Vue with the same variable name, app. But you also used var which makes it restricted to the containing scope (meaning, not a global variable). When you build an application using most build tools these days (webpack for example), the code you write is contained in a wrapping scope (a function). So the app variable that is the result of new Vue() is not accessible to you globally. If you wanted to make it accessible globally, you would probably write

window.app = new Vue()

However, you probably want to just rename it as well.

window.myApp = new Vue()

if you are going to call the template for app the same thing.

Community
  • 1
  • 1
Bert
  • 80,741
  • 17
  • 199
  • 164
0

Although, the answer to you question is to give your app variable a global scope with

window.app = new Vue({...});

Do you have Vue devtools extension in your Chrome browser? If not, please install it. With that installed, its now history to name my Vue instance something like window.app for the sake of debugging. Here is a link, you will find it really useful.

https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en

Oniya Daniel
  • 359
  • 6
  • 15