exported method and unexported methods in Vue.js component - javascript

I have two functions defined in a component. foo() is defined just within <script>, and fooExported() is defined in the body of export default {}
My understanding is that functions inside export default {} can be accessed in the template, so it sounds the "unexported" function foo() is a "private" function only available within the <script> scope (Is this correct?). What other difference do they have?
Also I'm trying to access this.$data in the "unexported" method but it shows undefined error. Is it not possible to access the data?
<template>
...
</template>
<script>
function foo(){
console.log(this.$data.message) // error: 'this' is undefined.
}
const bar = 123
export default {
data(){
return {
message: 'MyMessage'
}
},
methods: {
fooExported(){
console.log(this.$data.message) // this works.
}
}
}
</script>
<style scoped>
</style>

You are defining a component in a single-file component .vue file. This means that everything inside the default object is passed directly to the constructor method for a new Vue instance. Vue knows to automatically set the reference to this in any method defined within the methods object.
Your foo method is never handled by Vue, and the reference to this does not point to the Vue instance in the context of that function.
If you want your foo method to have a reference to the message data property, you could call the method from the created hook and pass the this.message as a parameter:
created() {
foo(this.message);
}
side note: as you can see above, you can reference data properties directly from this; you don't need to go through this.$data.

Related

Should/do I have to export returning class returned by another exported class in Javascript ES6?

Consider the following module:
export class Bar {
generateFoo() {
return new Foo(1);
}
}
class Foo {
constructor(fooValue) {
this.fooValue = fooValue;
}
doFoo() { console.log(this.fooValue); }
}
Should I export Foo too in any situation? Why/Why not?
Should I export Foo too in any situation? Why/Why not?
The only reason to export something from a module is if you want code from outside to be able to call it or reference it directly. If the only way you want your clients to be able to create Foo objects is by calling bar.generateFoo(), then there is no reason to export Foo. In Javascript, you can fully reference all Foo methods on an already constructed object without exporting the class itself.
If, on the other hand, you want some client of your module to be able to directly instantiate a Foo object with new Foo(someValue), then you would need to export Foo to make that possible.
Exporting a class is exporting the constructor function. So, you need to do that export if you want someone to be able to call the constructor directly (e.g. construct a new object with new Foo()). If they don't need to call the constructor directly, then you don't need to export it.

How to fix "this is undefined" in VueJS?

I've created a new component in VueJS and defined two methods.
One method is action(vuex) and another one is regular method.
actionTypes.js
const TOGGLE_PREVIEW = 'togglePreview';
component
method: {
...mapActions([actionTypes.TOGGLE_PREVIEW]),
onClickPreview: () => {
this.togglePreview();
}
It occurred an error; Uncaught TypeError: Cannot read property 'togglePreview' of undefined.
When a Vue instance is created Vue proxies data, methods, props and injections on the instance for easy access. To proxy methods it uses Function.prototype.bind ..
The bind() method creates a new function that, when called, has its
this keyword set to the provided value
However this doesn't work on arrow functions since their scope cannot be bound and they inherit their parent's scope. So the solution in your case is to use a normal function instead so that it's this scope can be correctly bound to the Vue instance.
methods: {
...mapActions([actionTypes.TOGGLE_PREVIEW]),
onClickPreview() {
this.togglePreview();
}
}

Making global functions to access vuex store

so I want to make a global function that I can access in every component of mine. So I stumbled upon Vue Plugins. They worked great, till I tried out my use case. I need to use some information from the vuex store in my plugin and return a true or false value.
So this is what I have tried
plugin.js
export default {
install (Vue) {
Vue.prototype.$rbac = (method, route) => {
$store.state.generic.user.routes.some(m => m.method.includes(method) && m.route==route)
}
}
}
main.js
import plugin from './utils/common/plugin'
...
Vue.use(plugin)
...
component.vue
<template>
...
<div v-if="$plug('post', '/project')></div>
...
</template>
But I get an error saying "ReferenceError: $store is not defined".
It kind of makes sense that I cannot access the store. The store only gets the value once the user logs in.
So is there any way I can make a global function that can access the store when it gets values?
You're getting the reference error because the $store variable hasn't been defined anywhere. It's not a local variable, nor is it a function parameter or global variable.
You probably meant to do this.$store; also make sure you use function () {} syntax and not () => {} because you don't want to bind this.
export default {
install(Vue) {
Vue.prototype.$rbac = function (method, route) {
this.$store.state.generic.user.routes.some(m => m.method.includes(method) && m.route == route)
}
}
}
You could also use a global mixin to do a similar thing instead of a plugin.

Variable undefined when used outside of component constructor

I'm working on a project with React and Electron and have an error. I have a component with a constructor that takes in props (which come in the form of two variables.) The constructor is instantiated in a separate file. The issue is that the variable works fine (for instance if do console.log to output it) in the constructor, but outside of it, the variables comes back undefined.
I've already tried using .bind to bind it, but that didn't help and it still turned up as undefined.
This is where the constructor is called:
const dropDown = new Dropdown({
editor,
monaco
});
Here is the constructor and an example of where I am trying to use the variables:
constructor(props) {
super(props);
// Define variables
this.editor = props.editor;
this.monaco = props.monaco;
// Returns correct object
console.log(this.monaco);
// Bind functions
this.changeLanguage = this.changeLanguage.bind(this);
this.filterFunction = this.filterFunction.bind(this);
this.dropDown = this.dropDown.bind(this);
}
changeLanguage(language) {
// Returns undefined all the time
console.log(this.monaco);
this.monaco.editor.setModelLanguage(this.editor, language);
}
I expect the variable to be the same in both the constructor and the functions elsewhere in the file, yet for some reason, it's only defined in the constructor.
You can use this.props.monaco. Or you can pass the props to the changeLanguage function if you rewrite it
changeLanguage(language, props) {
// Returns undefined all the time
console.log(props.monaco);
props.monaco.editor.setModelLanguage(this.editor, language);
}
and call it: this.changeLanguage('English', this.props)

(Vue) Inject variable into all components [duplicate]

I have a javascript variable which I want to pass globally to Vue components upon instantiation thus either each registered component has it as a property or it can be accessed globally.
Note:: I need to set this global variable for vuejs as a READ ONLY property
Just Adding Instance Properties
vue2
For example, all components can access a global appName, you just write one line code:
Vue.prototype.$appName = 'My App'
Define that in your app.js file and IF you use the $ sign be sure to use it in your template as well: {{ $appName }}
vue3
app.config.globalProperties.$http = axios.create({ /* ... */ })
$ isn't magic, it's a convention Vue uses for properties that are available to all instances.
Alternatively, you can write a plugin that includes all global methods or properties. See the other answers as well and find the solution that suits best to your requirements (mixin, store, ...)
You can use a Global Mixin to affect every Vue instance. You can add data to this mixin, making a value/values available to all vue components.
To make that value Read Only, you can use the method described in this Stack Overflow answer.
Here is an example:
// This is a global mixin, it is applied to every vue instance.
// Mixins must be instantiated *before* your call to new Vue(...)
Vue.mixin({
data: function() {
return {
get globalReadOnlyProperty() {
return "Can't change me!";
}
}
}
})
Vue.component('child', {
template: "<div>In Child: {{globalReadOnlyProperty}}</div>"
});
new Vue({
el: '#app',
created: function() {
this.globalReadOnlyProperty = "This won't change it";
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
In Root: {{globalReadOnlyProperty}}
<child></child>
</div>
In VueJS 3 with createApp() you can use app.config.globalProperties
Like this:
const app = createApp(App);
app.config.globalProperties.foo = 'bar';
app.use(store).use(router).mount('#app');
and call your variable like this:
app.component('child-component', {
mounted() {
console.log(this.foo) // 'bar'
}
})
doc: https://v3.vuejs.org/api/application-config.html#warnhandler
If your data is reactive, you may want to use VueX.
You can use mixin and change var in something like this.
// This is a global mixin, it is applied to every vue instance
Vue.mixin({
data: function() {
return {
globalVar:'global'
}
}
})
Vue.component('child', {
template: "<div>In Child: {{globalVar}}</div>"
});
new Vue({
el: '#app',
created: function() {
this.globalVar = "It's will change global var";
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
In Root: {{globalVar}}
<child></child>
</div>
If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze to freeze your object. Adding it to Vue's viewmodel won't unfreeze it.
Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))
you can use Vuex to handle all your global data
In your main.js file, you have to import Vue like this :
import Vue from 'vue'
Then you have to declare your global variable in the main.js file like this :
Vue.prototype.$actionButton = 'Not Approved'
If you want to change the value of the global variable from another component, you can do it like this :
Vue.prototype.$actionButton = 'approved'
https://v2.vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example
If you’d like to use a variable in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the Vue prototype:
Vue.prototype.$yourVariable = 'Your Variable'
Please remember to add this line before creating your Vue instance in your project entry point, most of time it's main.js
Now $yourVariable is available on all Vue instances, even before creation. If we run:
new Vue({
beforeCreate: function() {
console.log(this.$yourVariable)
}
})
Then "Your Variable" will be logged to the console!
doc: https://v2.vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example
If you want to make this variable immutable, you can use the static method Object.defineProperty():
Object.defineProperty(Vue.prototype, '$yourVariable', {
get() {
return "Your immutable variable"
}
})
This method by default will prevent your variable from being removed or replaced from the Vue prototype
If you want to take it a step further, let's say your variable is an object, and you don't want any changes applied to your object, you can use Object.freeze():
Object.defineProperty(Vue.prototype, '$yourVariable', {
get() {
return Object.freeze(yourGlobalImmutableObject)
}
})
A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY. I did like that:
Supposing that I have 2 global variables (var1 and var2). Just add to the index.html header this code:
<script>
function getVar1() {
return 123;
}
function getVar2() {
return 456;
}
function getGlobal(varName) {
switch (varName) {
case 'var1': return 123;
case 'var2': return 456;
// ...
default: return 'unknown'
}
}
</script>
It's possible to do a method for each variable or use one single method with a parameter.
This solution works between different vuejs mixins, it a really global value.
in main.js (or any other js file)
export const variale ='someting'
in app.vue (or any other component)
import {key} from '../main.js' (file location)
define the key to a variable in data method and use it.
Simply define it in vite configuration
export default defineConfig({
root:'/var/www/html/a1.biz/admin',
define: {
appSubURL: JSON.stringify('/admin')
}, ..../// your other configurations
});
Now appSubURL will be accessible everywhere

Categories

Resources