reading vue.js variables from the js console - vue.js

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?

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.

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

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)
}
}

Related

Avoid app logic that relies on enumerating keys on a component instance

in my complex Vue project I am getting this console warning:
[Vue warn]: Avoid app logic that relies on enumerating keys on a component instance. The keys will be empty in production mode to avoid performance overhead.
Unfortunately I can not find the reason for this warning just by the above message.
How can I track down the reason for this warning?
Check if your watching an entire route object anywhere in your code. Doing so throws that error (in my case).
Refer this vue documentation on watching routes
Accessing router and current route inside setup
The route object is a reactive object, so any of its properties can be watched and you should avoid watching the whole route object. In most scenarios, you should directly watch the param you are expecting to change.
Was able to fix this with the suggestion done by Glass Cannon.(https://stackoverflow.com/a/70205284/11787139)
To clarify and maybe help someone else: I was trying to send an Axios request to the server of which the data I sent through was composed of a direct component reference emitted by the component function.
Component
saveItem(){
this.saved = true;
setTimeout( this.resetState, 2500);
this.$emit('saveitem', this)
},
Parent
saveitem(e){
const data = {item : e}
axios.post(target, data, {headers . . .).then((response) => {}
})
The error disappeared when I instead fetched the index of the list item by doing so:
saveitem(e){
let item;
this.items.forEach( function(item, index, array) {
if(item.id == e.id) pointer = item
})
data.item = pointer
axios.post(target, data, {headers . . .).then((response) => {}
})
}
So I was also having this issue, but not for the reasons the accepted answer provided. It was occurring due to my Vuex store. After a lot of digging I discovered the cause was the presence of the "CreateLogger" plugin.
So if you're having this issue and it's not due to you watching an entire route, check if you're using the CreateLogger plugin in Vuex. That might be the culprit.
This happens for me when I pass this to a data object
data() {
return {
updateController: new UpdateController({
reportTo: this
})
}
}
This used to work fine with Vue 2 but causes this error in Vue 3.
Making this modification solved the problem for me.
data() {
return {
updateController: new UpdateController({
reportTo: () => this
})
}
}
I know this might be anti-pattern but I needed to inject partial reactivity to a non-reactive part of a JS library and this was the most not complicated way of achieving this that I can think of.
This happens to me when destructuring a ref without .value.
This was happening to me only in Firefox, and when I removed the Vue Dev Tools extension it stopped. After re-installing Vue dev tools it hasn't come back. Make sure you have the latest version of the Vue Dev Tools for your browser.

Access higher level component (parent) properties from subsubcomponents (children of children)

I am working on something which requires access to a property injected at the top level of a VueJS application. I can access the property by using:
this.$parent.$attrs.propertyname
This works nicely however, I am now wanting to be able to access the same item from a further subcomponent which works the same as above with an additional $parent call. Is there a way I can call this item at the top level in another way?
I have looked at $root and tested using Vue $vm console calls in the browser but doesnt work so far. I suspect theres a really easy way of doing this but I can't find it at the moment.
I have tried:
adding a return method from top level and calling it
$root
setting a prototype outside the vue application at the top level: Vue.prototype.$varname = '' and then attempting to assign on created() to this.$varname = this.mypropertyname
I suspect I am close somewhere or there is something I have missed.
I did plenty of fiddling and I have my answer.
So basically, my application passes data into the app from Laravel at the tag level. I have an overall template file for the app which is where I now set the data with a setter to root.
I will explain with some code:
Laravel:
<v-app token="abcdefg">
<template></template>
</v-app>
Thats the declaration of data passed into the app
On template.vue:
<script>
export default {
name: "template",
created() {
this.$root.setToken(this.$parent.$attrs.token);
}
}
</script>
We access the data and use the setter placed on app.js (root) to assign the data to an accessible $root location
app.js code:
const app = new Vue({
data() {
return {token: ''}
},
moment,vuetify,
router, store,
el: '#app',
methods: {
setToken(token)
{
this.token = token;
},
getToken()
{
return this.token;
}
}
});
A getter and setter available for the whole app to access. I may restrict access to the setter function later on but for now I am happy it works. Suggestions on restricting this will be nice.
Its now accessible via: this.$root.getToken()

Access Vue.js plugin from main.js

I'm creating a plugin and I just wonder why I can't access it in main.js file. Here's how Auth.js looks like:
const Auth = {
install(Vue) {
Vue.prototype.$isGuest = function () {
console.log('This user is a guest.');
}
Vue.prototype.$getAuthToken = function () {
console.log('Auth token will be returned.');
}
}
}
export default Auth
This is main.js:
import Auth from '#/helper/Auth'
Vue.use(Auth)
However, when I execute console.log(this.$isGuest()), it doesn't work. It actually returns the following:
main.js?1c90:25 Uncaught TypeError: this.$isGuest is not a function
The problem is that this method works when I call it in components such as Dashboard.vue and things like that.
I have a way to avoid calling isGuest method within main.js (I can call it in Layout.vue), but I'm more curious why it doesn't work in main.js.
Maybe because Vue hasn't been initialized yet, but even if I put the console.log() line at the end of the file, still doesn't work.
Thanks,
N.
If you are calling this.$isGuest() outside of Vue, you will get the error you describe. That's because this is not a Vue object. What this is depends on how you are building your code, but given you are using import it's probably the module.
Also, you are adding $isGuest to the prototype of Vue. That means that the function is only going to be available on actual instances of Vue objects. That is why it is available in your components.
If you want to use it in the main script, the only place you will be able to get to it is inside the Vue object in a lifecycle handler, method, or computed. For example:
new Vue({
mounted(){
console.log(this.$isGuest()) // this should work
}
})

VueJS - Define components in secondary .js file

I have this situation: I have an Laravel app that is not an SPA. But I use Vue in many components of my application, using single-file components and all of that.
But I have some components that I only want to load in some pages, for performance reasons. But, when I register a component in a second .js file, I always get an error like this:
Property or method "addresses" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
(found in )
My structure is something like this:
app.js
window.Vue = require('vue');
import ModalMessage from './../components/ModalMessage.vue';
import FlashMessage from './../components/FlashMessage.vue';
window.MainVue = new Vue({
el: '#app',
data: {
loading: false
},
components: { ModalMessage, FlashMessage }
});
All of this work's perfectly fine. But when I introduce a new .js file, I always get the error mentioned above.
Example:
account.js
window.UserAddresses = new Vue({
el: '#user-addresses',
data: {
addresses: []
},
methods: {
}
});
The HTML for the #user-addresses is:
<div id="user-addresses">
<table class="table">
<tr v-for="address in addresses">
<td>testing</td>
</tr>
</table>
</div>
And I always get the error:
Property or method "addresses" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
(found in )
In this internal page that generates the error, my JS files are included like this:
<script src="assets/js/app.js"></script>
<script src="assets/js/account.js"></script>
The account.js Vue instance is mounted before generates the error.
My question is: Is there a way to work with Vue in multiple .js files? I also didn't want to declare all my subcomponents data in my root Vue instance.
Is there a way to make this work?
UPDATE
I'm using webpack for compiling all files.
In general your top example looks just right and nothing I would see out of order. The problem though you describe with the addresses probably comes from how you use the UserAddresses.
I would guess you have it nested inside the #app element on the page.
The problem here is, you can't nest two Vue root instances in each other.
new Vue({...}) // get a Vue rootinstance
What you probably want to do is use a Component. You can use global components for this, and therefor it's fine to have one global root instance.
window.UserAddresses = Vue.component('user-addresses', {
data () {
return {
addresses: []
}
}
... // rest of your component code
}
You can get more information here: https://v2.vuejs.org/v2/guide/components.html

Instance Vue if element exists?

I'm building an app that a page has some vms, in others not. When we change from one page to another show the following warning:
[Vue warn]: Cannot find element: #element-id
How do I instantiate VMs only if there is the element on the page and avoid the error?
NOTE: I'm using Rails asset pipeline, so, all the javascript is concatenated into a single file.
There are no issues just leaving it as is. This is just a warning that only runs when debug mode is on, so you should have it turned off in production anyway.
If you want to get rid of it, just check if the element exists before launching Vue -
if(document.getElementById("element-id")){
new Vue({...})
}
Ref: How to check if element exists in the visible DOM?
This is a bit of an old question. I found this Vue example being useful
https://v2.vuejs.org/v2/api/#Vue-extend
So you can create a Vue class and initiate it only if the dom element is present in the DOM.
// create constructor
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
}
}
})
// create an instance of Profile and mount it on an element
if(document.getElementById("element-id")){
new Profile().$mount('#element-id')
}