Where to use the main variable of a new vue instance - javascript

I'm obviously missing the point somewhere here, but where does one use the main variable of a new vue instance?
I'm new to vue.js (obviously) and whilst reading various documentation I can't help notice that each new vue instance starts with something like var app = new Vue({ but then in the examples I've read this app variable doesn't get referenced again in the js or html. The code works fine without referencing it anywhere.
Could someone please kindly advise on where or why I would use the app variable?
Many thanks

It's completely not required to capture the result of new Vue() if you don't need or want to.
The reason it's done is primarily for testing (ala from the console) or for interaction with external libraries. Because all of the methods and data of the Vue are available on the variable it's possible to call those methods and use that data from outside Vue.
For example, let's say I have some logic on my page completely outside Vue that has some data I want to use inside my Vue.
const externalData = {message:"I'm some interesting data."}
const myVueApp = new Vue({
el: "#app",
data:{
message: null
}
})
myVueApp.message = externalData.message
Here the code is setting the message property of Vue from outside Vue.
This is useful primarily when you have existing code, and you are integrating Vue into that existing environment.
Another scenario is just plain testing. Open your console and run the snippet below. Change the context to the snippet's javascript:
And then type
app.message = "Hey, this is nifty!"
And the new message will be reflected in the Vue.
console.clear()
const app = new Vue({
el: "#testing",
data:{
message: "Change me from the console!"
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="testing">
{{message}}
</div>

Related

How to call Vue instance in chrome console, if he created in a separated file

How to call Vue instance in chrome console, if it created in a separated file new Vue({ ... }). Like console.log(vm.user.id)
new Vue({
el: '#app',
data: {
message: {
id: 1,
title: 'TEST VUE'
}
}
});
If you have the Vue DevTools installed it will create aliases for your Vue instances when you click on them:
Note the light text to the right of the component name. It may be hard to see on some screens.
In the picture above, $vm1 and $vm2 are accessible in the console and will refer to the corresponding Vue instances.
As you click around in the DevTools these aliases will change. $vm0 will refer to the last component you clicked on.
The best way to do this is by using the Vue Chrome extension as described by #skritle. You also get nice UI with bells and whistles to look at the data, computed properties etc if that's what you need.
However, I've had to do this in environments which didn't have the extension. In those scenarios, you can just add the instance to the global object window (browser) or global (nodejs).
const app = new Vue({...});
window.$appRef = app; // Remove this line for release
Then in load the app in the browser and you can access it in the console :
console.log($appRef)
This should only be used as an emergency escape hatch because it pollutes the global object (potentially causing name collisions and memory leaks) and should be cleaned up after use. You can also wrap it in an if condition to ensure it is used only during development
if (
process.env.NODE_ENV !== 'production' &&
process.env.NODE_ENV !== 'test' &&
typeof console !== 'undefined'
){
window.$appRef = app;
}
Question already has it's accepted answer, but it's worth mentioning the recommended pattern to capture different instance for vue - https://v2.vuejs.org/v2/guide/instance.html#Creating-a-Vue-Instance
Just make your own custom variable for different vue instances
// Use var to mark this variable a global, make sure it's wrapped directly to global execution context, so that you can get it at window scope
var vueInstance1 = new Vue({
el: '#app1',
data: { title: 'Vue Instance 1' }
})
var vueInstance2 = new Vue({
el: '#app2',
data: { title: 'Vue Instance 2' }
})
console.log('Instance 1- ', vueInstance1.title ) // Easily access to instance 1
console.log('Instance 2- ', vueInstance2.title ) // Easily access to instance 2
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app1">{{ title }}</div>
<div id="app2">{{ title }}</div>

How to set vue-data after new vue and work for data-binding

e.g:
I need to add data-value after new vue and work for data-binding.
why i need to do that :
I know it's work if i declare first on new Vue object.
But there's a old project with a lot of layout-subject-page,if i need to add a vue global varible then i need to edit every page's vue data-value.
what i expected :
var app = new Vue({
el: '#app',
data: {}
})
app.$data.message = "test"
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h1>{{ message }}</h1>
</div>
It can't be done.
Vue runs internal setup on the initially declared data properties which won't happen if you try to declare them later.
From the docs:
Vue does not allow dynamically adding new root-level reactive properties to an already created instance.
You can add new object/array items using Vue.set if that helps you.

Why doesn't an unassigned Vue instance get garbage collected?

Here's the standard way to use VueJS on the HTML page (without bundles). No assignment.
<script>
new Vue({
el: '#root',
data: {
title: 'Hello'
}
});
</script>
Why Garbage Collector doesn't collect this Vue object?
When you instantiate a Vue object, it actually mounts itself to the DOM element, here #root element, as briefly hinted in this documentation page The Vue Instance > Instance Lifecycle Hooks.
By using Developer Tools in your browser, like in Chrome, you can open the console tab and prompt, type console.log(window.$vm0); and hit enter. And you get access to your Vue runtime instance even it was not assigned to a variable:
> Vue {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: Vue, …}
I've opened another question on how to properly access the Vue instance if it wasn't assigned to a variable during instantiation.
The main point, as an answer to this current question, is that there is actually variable assignment / DOM mounting happening behind the scenes by Vue itself, so that is why garbage collection is not triggering.
PS. There is a detailed documentation article Avoiding Memory Leaks in relation to handling Garbage Collection in a Vue application.
A Vue application consists of a Vue instance created with new Vue and mounted in DOM element with id '#root'. Vue is running all this magic behind the scene that's why garbage collector will not collect Vue object.
In addition to data properties, Vue instances expose a number of instance properties and methods. These are prefixed with $ to differentiate them from user-defined properties. For example:
var data = { title: 'Hello' }
var vm = new Vue({
el: '#root',
data: data
});
// If you check below code
vm.$data === data // => true
vm.$el === document.getElementById('root') // => true

Embed Vue component within Shopify store

Within a product page, I am trying to display a custom Vue component. For brevity, the component displays some information from a Firebase database based on the given product id.
I originally tried to make this a Shopify app so I could access their APIs. I implemented OAuth and can retrieve the required information. However, actually including the component within the store has been unsuccessful.
What is the best way of including Vue inside Shopify?
I have tried including the script files directly inside the template files, inside snippets, and included them within the global scripts tag. But nothing I have tried has been able to render even a simple component.
Inside product.liquid:
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.js"></script>
<div id="app">
{{ message }}
</div>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
</script>
Inside Vue developer tools the component appears inside the DOM but the "Hello Vue!" message does not appear as it should.
There are no other errors in the console. Which is most puzzling.
Any insight into the proper way of including Vue into Shopify would be greatly appreciated.
Liquid files will by default parse {{ }} tags. So you need to change your templating mechanism. Below is updated code which works in Shopify Liquid files -
<div id="app">
${ message }
</div>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
delimiters: ['${', '}']
})
</script>
Basically, i have added delimeters which vue will check to find templates and they are different from Shopify Parsing which will result in shopify not parsing those holders. You can read up more about vue delimeters here - Link

Declaring data in Vue with components

According to the docs, this is how you declare data in Vue:
data: {
name: 'Vue.js'
}
However, when I do that it doesn't work and an error shows in the console:
The "data" option should be a function that returns a per-instance value in component definitions.
I change it to the following and then it works fine:
data() {
return {
name: 'Vue.js',
}
}
Why do the Vue docs show the top bit of code when it doesn't work? Is there something wrong on my end?
Edit: This only happens when using components.
In a root Vue instance (which is constructed via new Vue({ . . . }), you can simply use data: { . . . } without any problems.
When you are planing to reuse Vue components using Vue.component(...) or using "template" tag, Use data attribute as a function.
Please review the corresponding section of the Vue.js documentation for more information regarding this problem
https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function
You should declare data in Vue.js by doing
var app = new Vue({
el: '#app', //This is the container in which Vue will be in. The #app means the id of the container is app
data: {
}
});
It turns out you need to declare data in components different than when you set it on a Vue object.
Instead, a component’s data option must be a function, so that each instance can maintain an independent copy of the returned data object:
More: Vue docs

Categories

Resources