Vuejs - How to call the mounted function of main.js from another Js file - vue.js

This is the code I have given in commonValidation.js.
commonValidation.js:
this.$validator.localize('en', {
messages: {
required: (field) => '* ' + field + ' is required'
},
attributes: {
email: 'Email'
}
})
I want to call the above file in main.js inside the mounted function
like below. But it's not working. If I given those validation(from commonValidation.js) inside the mounted()(in main.js) method it's working.
main.js:
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
import App from './App'
import router from './router'
import VeeValidate from 'vee-validate';
import commonValidation from './commonValidation'
Vue.use(VeeValidate);
Vue.use(BootstrapVue);
new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
},
mounted()
{
commonValidation
}
})
Please help me to call the commonValidation.Js inside the mounted() in main.js . Thanks in advance.
This is my complete commonValidation.js
export default {
mounted() {
this.$validator.localize('en', {
messages: {
required: (field) => '* ' + field + ' is required'
},
attributes: {
email: 'Email'
}
})
}
}

You are exporting an object in commonValidation.js file.
An object cannot be invoked like a function.
I think your intent is to use a mixin. A mixin is nothing but an object that contains reusable component options as its properties.
So just register the mixin on the root component in your main.js file:
//main.js
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
import App from './App'
import router from './router'
import VeeValidate from 'vee-validate';
import commonValidation from './commonValidation'
Vue.use(VeeValidate);
Vue.use(BootstrapVue);
new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
},
mixins : [commonValidation]
}

Related

commit api data to vuex from component

I am trying to push data from an api call to my store, but I keep getting errors like commit is undefined and dispatch is undefined.
If I understood documents correctly I can only manipulate state from components by creating mutations? been going round in circles for an hour now and would appreciate some guidance.
in main.js
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'
import router from './router'
import 'es6-promise/auto'
Vue.config.productionTip = false
new Vue({
router,
render: (h) => h(App),
store: store,
}).$mount('#app')
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
images: [],
},
mutations: {
addImages(state, newImages) {
state.images = []
state.images.push(newImages)
},
},
})
Header.js component:
<template>
<div>
<h1>Nasa Image Search</h1>
<div class="search-container">
<form action="/action_page.php">
<input v-model="searchWord" type="text" placeholder="Search.." name="search" />
<button v-on:click.prevent="search" type="submit">Search</button>
</form>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Header',
data: () => ({
searchWord: "",
//images: [],
}),
methods: {
search() {
let url
this.searchWord
? url = `https://images-api.nasa.gov/search?q=${this.searchWord}&media_type=image`
: url = `https://images-api.nasa.gov/search?q=latest&media_type=image`
console.log(url) //bug testing
axios
.get(url)
.then(response => {
const items = response.data.collection.items
console.log(items)
this.$store.commit('addImages', items)
console.log(this.$store.state.images)
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>
Your code is perfectly fine, please create a new file store.js as below and import it in main.js and it will work. In newer version of vuex eg 4.0 we do have createStore function using which we can include store code in main.js file itself.
store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: { images: [], },
mutations: {
addImages(state, newImages) {
state.images = []
state.images.push(newImages)
},
},
});
main.js
import Vue from "vue";
import App from "./App.vue";
import { store } from "./store";
import router from './router'
import 'es6-promise/auto'
Vue.config.productionTip = false;
new Vue({
router, store,
render: h => h(App)
}).$mount("#app");
in Vue 3 with Vuex 4 -> We can have store code inside main.js as below. doc link https://next.vuex.vuejs.org/guide/#the-simplest-store
import { createStore } from 'vuex'
import { createApp } from 'vue'
const store = createStore({
state () {
return {
}
}
})
const app = createApp({ /* your root component */ })
app.use(store)
Normally I create my Vuex 'store' in a separate file and import it into main.js.
I did a local experiment where I declared 'const store' in main.js AFTER instantiating new Vue() in main.js, as you are doing, and am getting errors.
Try declaring 'const store' BEFORE new Vue().

Can I have a global mixin and a imported one on Vue?

so, I have this Vue 2 project with a global mixin:
import Vue from "vue";
import App from "./App";
import router from "./router";
import store from "./store";
import vuetify from "#/plugins/vuetify"; // path to vuetify export
import VueLayers from "vuelayers";
require("./assets/css/style.css");
import "vuelayers/lib/style.css"; // needs css-loader
Vue.config.productionTip = false;
Vue.use(VueLayers);
Vue.mixin({
data() {
return {
placeholderOptions: [
{
item: "ex1",
valor: 0
},
{
item: "ex2",
valor: 1
}
]
};
}
});
/* eslint-disable no-new */
new Vue({
el: "#app",
router,
store: store,
vuetify,
components: { App },
template: "<App/>"
});
AND I have a folder with other mixins separated by file, that I can import on my components if I want. Example of mixin of this folder:
import parametros from "../mockup/parametros.json";
export default {
data() {
},
methods: {
getOptions(parametro) {
let options = [];
parametros[parametro].forEach((item, i) => {
options.push({
item: (i + 1) + " - " + item.nome,
value: i + 1
})
})
return options
}
}
}
But when I import this mixin on my component, It's like all the components in the app cannot see the global mixin anymore. I can't use more than one mixin, if one of them is a global one? Or am I doing something wrong? Here is a example of importing the mixin of my mixin's folder, having the global one.
<script>
import parametrosMixin from "../../../mixins/parametrosMixin.js";
export default {
name: "AtributosGerais",
mixins: [parametrosMixin],
...etc
};
</script>
Thanks!
So, I figured out the problem, I was declaring a data() on my mixin that was returning nothing, as you can see on the question :(

How can I fix '[vuex] unknown action type: lookupName' within my Vue component?

I am having an issue calling up an action from my Vue component using this.$store.dispatch('lookupName'). I have tried console logging the this.$store method, but the actions within it are empty.
Main.js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import { findCertificate } from '#/api';
Vue.use(Vuex)
const state = {
// single source of data
nameLookup: {},
}
const actions = {
// asynchronous operations
lookupName(context, form){
return findCertificate(form)
}
}
const store = new Vuex.Store({
state,
actions,
mutations,
getters
})
export default store
Vue Component
import VueRecaptcha from 'vue-recaptcha';
import { mapGetters, mapActions} from 'vuex'
export default {
created() {
},
methods: {
...mapActions({
lookupName: 'lookupName'
}),
...mapActions({
add: 'lookupName'
}),
onCaptchaVerified: function(recaptchaToken){
this.$refs.recaptcha.reset();
console.log(this.$store.dispatch('lookupName', this.form))
},
}
}
Why am I still getting this error? I have looked up many other people's questions about similar issues, but those solutions did not work for me.

Store referenced but not defined

Hey I have some bullshit issue with store not being defined. Any advice so I can move on and finish this software build? Store and contents of store appears in Vue Inspector tools. When put inline like below it breaks and renders blank - no DOM content inside App component.
App.vue offending excerpt
<div v-if="$store.state.showPreloader == true" id="preloaderWrap">
<div id="preloader"></div>
</div>
Store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
stuff
}
const mutations = {
stuff
}
const getters = {
stuff
}
const actions = {
stuff
}
export default new Vuex.Store({
state: state,
mutations: mutations,
getters: getters,
actions: actions
})
Main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import VueGraph from '../node_modules/vue-graph'
import VueMaterial from '../node_modules/vue-material'
import 'vue-material/dist/vue-material.min.css'
Vue.config.productionTip = false;
Vue.use(VueGraph);
Vue.use(VueMaterial);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
You need to init Vue with store:
new Vue({
el: '#app',
router,
store: store,
components: { App },
template: '<App/>'
})

vuejs2: How to pass vuex store to vue-router components

In case when vue-router is not used, store can be passed to child components when declaring new Vue()
But I am using both vue-router and vuex. In this case how can I make store available to components. For e.g. my store.js is typical:
import Vue from 'vue'
import Vuex from 'vuex'
import jwt_decode from 'jwt-decode'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex);
Vue.use(VueAxios, axios);
export const store = new Vuex.Store({
state: {
jwt: localStorage.getItem('t'),
endpoints: {
obtainJWT: 'http://0.0.0.0:8000/auth/obtain_token',
refreshJWT: 'http://0.0.0.0:8000/auth/refresh_token'
}
},
mutations: {
updateToken(state, newToken){
localStorage.setItem('t', newToken);
state.jwt = newToken;
},
removeToken(state){
localStorage.removeItem('t');
state.jwt = null;
}
},
actions:{
obtainToken(username, password){
//commented code
},
refreshToken(){
//commented code
},
inspectToken(){
//commented code
}
}
});
My main.js file is as below:
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
import { store } from './store'
console.log(store)
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
And router/index.js file is as below:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import Signup from '#/components/signup/Signup'
import store from '../store.js'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/login',
name: 'Login',
component: function (resolve) {
require(['#/components/login/Login.vue'], resolve)
}
},
{
path: '/signup',
name: 'Signup',
component: Signup
}
]
})
Now how can I pass store to my Signup component. Even though I am passing store in new Vue() it is not available in Signup component
I think the problem is that you importing store and you use the ../store.js,but when you import js file you dont have to use the .js so it has to be import store from '../store'
Also you dont have to pass the vuex store in components using vue-router.
So follow below the installation of vuex store and vue-router!
Vuex Store:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
propertiesName: 'PropValue'
},
getters: {},
mutations: {},
actions: {}
});
Vue-Router:
import Vue from 'vue'
import Router from 'vue-router'
import Page from '#/components/Page.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/Page',
name: 'Page',
component: Page,
},
//other routes
],
mode: 'history',
scrollBehavior(to, from, savedPosition) {
if(savedPosition){ //when use press back button will go at the position he was on the page
return savedPosition
}
if(to.hash){ //if has a hash positition to go
return { selector: to.hash } //go to the page in scrolled Position
}
return { x:0, y: 0 } //go to the page in scroll = 0 Position
}
})
main.js:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { store } from '../store/store'
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
Note:Doing that,now you have access of router and store in all your components
To use the store in your components:
this.$store.state.propertiesName
To use the router in your components:
this.$router.push({name: 'Page'})