access component from .js file vuejs - vue.js

I am using: https://www.npmjs.com/package/vue-loading-overlay
My main.js file looks like:
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
And App.vue:
<template>
<div id="app">
<loading
:active.sync= "isLoading"
:can-cancel= "false"
:is-full-page= "false">
</loading>
<router-view></router-view>
</div>
</template>
<script>
//import Vue from 'vue';
import Loading from 'vue-loading-overlay';
import 'vue-loading-overlay/dist/vue-loading.css';
//Vue.use(Loading);
export default {
data() {
return {
isLoading: true
}
},
name: 'App',
components: {
Loading
}
}
</script>
<style>
</style>
This seems to work fine, but how can I manipulate the isLoading to be true or false, from main.js? I might be building a function or something in main.js for future use, and instead of having the <loading> on each view page, I would prefer to be able to control it globally some how.

I haven't tested this, but based on the referenced answer in my comment, this might work:
main.js
new Vue({
el: '#app',
props: ['isLoading'],
components:{App},
template: '<App v-bind:isLoading="true">'
})
You would have to make isLoading a prop in App.vue. The v-bind part above should make the prop reactive.
Also, you could create a bus and send events from main.js to App.vue, then update isLoading accordingly.

You should use store for it.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let store = new Vuex.Store({
state: {
isLoader: false,
},
getters: {
isLoader(state) {
return state.isLoader
},
},
mutations: {
isLoader(state, status) {
state.isLoader = status
},
},
actions: {
isLoader({commit}, status) {
commit('isLoader', status)
},
}
})
everywhere in your application you can set the isLoader to true using dispatch
vue.$store.dispatch("isLoader", true/false);

Related

How to access the window object in vue js?

I have this vue js component:
<template>
<div>
hello world
</div>
</template>
<script>
export default {
name: 'mycomp',
data: function () {
console.error("window.google_recaptcha_public_key", window.google_recaptcha_public_key);
return {
}
},
mounted() {
let app = this;
console.error("window.google_recaptcha_public_key2", window.google_recaptcha_public_key);
},
}
</script>
<style scoped lang="scss">
</style>
returns:
window.google_recaptcha_public_key undefined
window.google_recaptcha_public_key2 undefined
where can I leave painless and happy all global configuration?
notice this configuration lives in my laravel backend. So I wont copy paste all values from the backend to the front end
U can use Vue.prototype in main.js file, or in file you import Vue
Vue.prototype.Hereanyname = window.hereanyname;
and in your Vue application, you can use it
Hereanyname.thefunction
Real example on Laravel
in main.js
import Vue from 'vue';
Vue.prototype.Routes = window.routes;
new Vue({
el: '#app',
template: '<App/>',
components: {App}
});
in your application
:href="Routes.route('laravel.route.here')"
So for your case
import Vue from 'vue';
Vue.prototype.GoogleRecaptcha = window.google_recaptcha_public_key;
new Vue({
el: '#app',
template: '<App/>',
components: {App}
});
inside application
mounted() {
console.log(this.GoogleRecaptcha)
}
In Vue3, you no longer have the global Vue instance, so you need to assign the window as a global property on your app...
// main.js
app.config.globalProperties.window = window
Then in your components, window will just work.
This info is from an impeccable source.
You should save your window variable in Vue.prototype
main.js
Vue.prototype.$authUser = window.authUser;
After that, you can access your data as follows:
Vue template
<div v-text="$authUser.name"></div>
Vue script
let name = this.$authUser.name;
window is available in the vuex store. This may help if you need to mutate the window property synchronously with other actions/mutations, give you a chance to validate what goes into it, or catch an error if the variable you intend to put there isn't available.
export default new Vuex.store({
state: {
windowFoo: window.foo,
googleRecaptcha: window.google_recaptcha_public_key
},
getters: {
windowFoo: (state) => state.windowFoo,
googleRecaptcha: (state) => state.googleRecaptcha
},
actions: {
barThenFooThenBaz({ commit }, { foo }) {
// ... do some other required actions first
commit("setWindowFoo", foo);
// ... do some dependent actions next
}
},
mutations: {
setWindowFoo(state, foo) {
state.windowFoo = foo;
}
}
});
Then from your Single File Component...
//....
computed: {
windowFoo() {
return this.$store.getters.windowFoo;
},
googleRecaptcha() {
return this.$store.getters.googleRecaptcha;
}
},
methods: {
async barThenFooThenBaz(foo) {
await this.$store.dispatch({
type: "barThenFooThenBaz",
foo: foo
});
// ... do something dependent on windowFoo being set
}
}
//....
Although the other answers here are totally acceptable, I've had issues using the Vue instance with Vue.prototype in main.js as our project has gotten larger, so I hope this helps!
Provide/Inject works nicely. Here's an example with Vue 3:
main.js
const app = createApp(App)
app.provide('recaptcha_key', window.google_recaptcha_public_key)
app.mount('#app')
MyComponent.vue
<script setup>
const { inject } from 'vue'
const recaptchaKey = inject('recaptcha_key')
</script>

Call vuex store without mapState

So I'm experimenting with a new project created with vue cli, where I am using router and VueX
So in my HelloWorld.vue file, I've got this code in the script section:
import { mapState } from 'vuex'
export default {
name: 'hello',
computed: mapState({
msg: 'nombre'
}),
Is there a more direct way of calling values in the state?, like for example I would like to do
msg: store.nombre
My vuex store is defined in the root main.js like this:
//vuex
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
nombre: "POS vuex"
}
});
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
Actually I was looking for this way:
msg: this.$store.state.nombre
(I was missing the ".state." part)
As soon as you're using mapState as computed you can actually call these states with this in that component - in the template or script section:
Use the ... operator on your mapState and you're done:
Example:
Your store:
const store = new Vuex.Store({
state: {
nombre: "POS vuex",
otherState: "abc",
anotherState: "efg"
}
});
Your component:
<template>
<div id="test">
{{ nombre }}
{{ otherState }}
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'hello',
methods: {
logState() {
console.log(this.anotherState);
}
},
computed: {
...mapState(["nombre", "otherState", "anotherState"]),
}
}
</script>
In addition to the the mapState helper
computed: {
...mapState('moduleOne', ['keyOne', 'keyTwo'])
}
which lets you access the values via this.keyOne and this.keyTwo inside your component.
You can also add your store to the root vue instance and access your state inside your components via the global this.$store directive.
this.$store.module.keyOne
this.$store.module.keyTwo
Additionally if you need to access your store from outside your components you can also export the store and import it directly from non-component code.
If you export your store:
import Vue from 'vue'
import Vuex from 'vuex'
import moduleTwo from './modules/moduleOne'
import moduleOne from './modules/moduleTwo'
Vue.use(Vuex)
const store = new Vuex.Store({
strict: true,
modules: {
moduleOne,
moduleTwo
}
})
export default store
You can import it anywhere you need to access state, getters, actions, and mutations.
import store from '#/store'
console.log(store.state.moduleOne.keyone)
store.dispatch('moduleOne/actionOne', { keyOne: valOne })
store.getters['moduleOne/getterOne']
store.commit('moduleOne/mutationOne', data)
Call you'r state in created method of vuex.
THanks

I can't access to Vuex data: using vue-cli webpack

Right now, I'm trying to show the contents of state object from store.js on my App.vue.
I've tried vuex examples on Medium and other website, but I'm keep failing: non of them worked: some of them even gave me a WebPack config error.
My App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
<h1>TEST</h1>
</div>
</template>
<script>
import Store from './store/index'
export default {
name: 'App',
Store
}
</script>
My store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
alpha: ['1st data']
},
mutations: {
ADD ({ alpha }) {
const beta = 'new!'
state.alpha.push(beta)
}
}
})
My main.js
import Vue from 'vue'
import App from './App'
import Vuex from 'vuex'
import store from './store/index'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
})
You shouldn't be importing the store in App.vue. It only needs to be included in main.js and passed as an option when constructing the Vue instance. Within a component, the store is thereafter accessible via this.$store.
Second, your mutation should receive a context object as it's first parameter. context consists of properties such including state and commit. Those are the ways in which you access state within a mutation.
// notice context is the first parameter
mutations: {
ADD (context, { param }) {
const beta = 'new!'
context.state.alpha.push(beta)
})
}
// you can also deconstruct context like this
mutations: {
ADD ({state}, { param }) {
const beta = 'new!'
state.alpha.push(beta)
})
}
I also changed the way alpha to param. You don't receive the state's properties unless you destructure even further.
The problem is that in your main.js is missing Vue.use(veux)
you should have something like this:
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import store from './store'
Vue.use(Vuex) // <-- Add this
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
template: '<App/>',
components: { App }
})

Property or method "msg" is not defined on the instance but referenced during render

While trying out Vue and Vuex, i stumbled upon the following error message:
[Vue warn]: Property or method "msg" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
I fail to understand and solve this issue, mainly because msg is defined in the code under data. It's probably doesn't related directly to Vuex, but i faced it only when i started using Vuex.
Here is my code:
main.js:
import Vue from 'vue'
import App from './App.vue'
import { store } from './store.js'
Vue.component('app', App);
var vApp = new Vue({
el: '#app',
store,
render: h => h(App),
})
App.vue:
<template>
<div id="app">
<div v-text="msg"></div>
<input id="name-b" class="input" v-model="nameB" type="text" placeholder="Name B">
</div>
</template>
<script type = "text/javascript">
module.exports = {
name: 'app',
data() {
return {
msg: 'boooo'
}
},
computed: {
return {
nameB: {
get() {
this.$store.state.nameB
},
set(value) {
this.$store.commit('setName', value);
}
},
}
</script>
<style>
</style>
store.js:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
nameB: '',
},
mutations: {
setName: function(state, name) { state.locationName = name},
},
});
Thanks.
Problem solved.
It was a curly brackets issue and possibly the return in computed that is not needed...
This is a confusing error message.

Vue-i18n doesn't work properly in the data method?

Multilingual folder i18n contents are as follows:
src
lang
cn.js
us.js
index.js
The contents of the index.js file are as follows:
import VueI18n from 'vue-i18n'
import Vue from 'vue'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'cn',
messages:{
'cn': require('./lang/cn'),
'us': require('./lang/us')
}
})
export default i18n;
mina.js
import Vue from 'vue'
import App from './App'
import router from './router'
import i18n from './i18n' //import mutil-lang
Vue.config.productionTip = false
var VueCookie = require('vue-cookie');
Vue.use(VueCookie);
new Vue({
el: '#app',
router,
template: '<App />',
i18n, //import mutil-lang
components: { App }
})
I want to say the write to template tags and JS code, as follows:
<template>
<div class="wrap">
{{ $t('message.the_world') }}
</div>
</template>
and
export default {
name:'dkc-exchange-detail' ,
data(){
return {
showExchangeTypes: false,
exchangetItems: [
//this.$t('message.the_world') Want to get the character of the corresponding language
{id: 1, text: this.$t('message.the_world')},//
{id: 2, text: this.$t('message.the_world_2')}
],
}
},
}
When I switch over multilingual methods:
methods:{
choiceLang: function(lang){
if(lang === this.currentLang)
return;
this.currentLang = lang;
this.showLangSelecor = false;
this.$cookie.set('lang', this.currentLang.lang, { expires: 7 });
window.location.reload();
},
},
In template, multi language syntax behaves as expected, but JS grammar is not. It pays attention to display a certain language,Where is the problem? Thanks!
showLangSelector is spelled wrong. Also reloading the page will destruct the whole vue component and reconstruct one from scratch, so the this.foo = bar settings above reload won't work, because in the reloaded page, they never happened, you only have a fresh new vue component.