Let's say I had this:
var app = new Vue({
el: '#app',
data: {
message: Math.random()
}
})
And let's say that I wanted to see what value data.message had been assigned in the JS console. How would I do this?
Superficially it seems like doing console.log(app.data.message)
would do the trick but when I try to do that I get a Uncaught TypeError: Cannot read properties of undefined (reading 'message')
error. In fact, it turns out that app.data
is undefined.
So how can I do this?
Here's a JS fiddle with this code:
https://jsfiddle.net/dfzun3by/4/
That code is based off of https://v2.vuejs.org/v2/guide/?redirect=true#Declarative-Rendering
As a corollary to this question... in some production code that I'm now responsible for we don't have that - we have something more akin to this in a *.vue file:
export default {
data() {
return {
message: Math.random()
}
}
}
I tried to do console.log(app)
in the JS console of the page that that corresponds to and got a Uncaught ReferenceError: app is not defined
error so how could I do the same thing in the production code?
CodePudding user response:
Sounds like the Vue.js Devtools extension might be beneficial for you, it'll allow you to see the values of all variables that are available to the Vue template (so everything in data
).
https://devtools.vuejs.org/guide/installation.html
CodePudding user response:
You can access the root instance from JS console with:
document.getElementById('app').__vue__.message
or
app.$options.data().message
For inspecting vue SFC, it is better to use Vue Devtools.
CodePudding user response:
You can reference that value doing console.log(this.message). If you want to log the value every time it changes, you can create a watcher for the message and include "console.log(this.message)" in there.
watch: {
message() {
console.log(this.message)
}
}