MapState not found Vuex4 with Vue3 in MVC project - javascript

In my MVC project i am using Vue3 with Vuex4 and they are working but i have got one issue with mapState.
if I use these import statements i am getting this error:
import Vue from 'vue';
import Vuex from 'vuex';
1 Uncaught SyntaxError: Cannot use import statement outside a module
So i add these files in my _Layout page to fix it
<script src="~/lib/vue/vue.global.js"></script>
<script src="~/lib/vuex/vuex.global.js"></script>
So far it is working. But when i want to use mapState, i am stack! not sure how to fix it,
import { mapState } from 'vuex';
I searched for mapStaate.js file but couldn't find or the files i find has just few lines of code and not working...
const store = new Vuex.Store({
state: {
count: 0
}
})
const homeIndex = {
data() {
return {
}
},
computed: mapState({
count: state => state.count,
})
}
Vue.createApp(homeIndex).mount("#app");

The import statement is for modules. You don't need the module syntax since you are loading the scripts directly. Remove the import statement and use Vuex.mapState like you used Vuex.Store:
computed: Vuex.mapState({
count: state => state.count,
})
If you prefer, you can use object destructuring to give a similar appearance to imports. Then you could use mapState as you did in the question:
const { mapState, mapGetters, mapActions } = Vuex;
computed: mapState({
count: state => state.count,
})

Related

How to use $axios Nuxt module inside of setup() from composition API?

The docs say to use this.$axios.$get() inside of methods/mounted/etc, but that throws TypeError: _this is undefined when called inside of setup(). Is $axios compatible with the composition API?
To clarify, I'm specifically talking about the axios nuxt plugin, not just using axios generically. https://axios.nuxtjs.org/
So for instance, something like this throws the error above
export default {
setup: () => {
const data = this.$axios.$get("/my-url");
}
}
import { useContext } from '#nuxtjs/composition-api';
setup() {
const { $axios } = useContext();
}
Alright, so with the usual configuration of a Nuxt plugin aka
plugins/vue-composition.js
import Vue from 'vue'
import VueCompositionApi from '#vue/composition-api'
Vue.use(VueCompositionApi)
nuxt.config.js
plugins: ['~/plugins/vue-composition']
You can then proceed with a test page and run this kind of code to have a successful axios get
<script>
import axios from 'axios'
import { onMounted } from '#vue/composition-api'
export default {
name: 'App',
setup() {
onMounted(async () => {
const res = await axios.get('https://jsonplaceholder.typicode.com/posts/1')
console.log(res)
})
},
}
</script>
I'm not sure about how to import axios globally in this case but since it's composition API, you do not use the options API keys (mounted etc...).
Thanks to this post for the insight on how to use Vue3: https://stackoverflow.com/a/65015450/8816585

How to initialize NCForms library in VueJs

I'm new to Vue CLI, and I'm trying to build a small application. As part of this I want to generate some forms.
I've tested a few libraries, and NCForms seems to do all I need to do. (specifically, I need to handle capturing of multiple arrays).
I tried to initialize the library as described in the documentation - but it fails in the Template saying that it can't find some of the element-ui components.
I'm pretty sure that I've followed the instructions properly - but I must be missing something small.
My main.js file looks like this:
import 'ant-design-vue/lib/style/index.less' // antd core styles
import './#kit/vendors/antd/themes/default.less' // default theme antd components
import './#kit/vendors/antd/themes/dark.less' // dark theme antd components
import './global.scss' // app & third-party component styles
import Vue from 'vue'
import VuePageTitle from 'vue-page-title'
import NProgress from 'vue-nprogress'
import VueLayers from 'vuelayers'
import BootstrapVue from 'bootstrap-vue'
import VueFormulate from '#braid/vue-formulate'
// Form generator: Vue-Form-Generator: https://github.com/vue-generators/vue-form-generator
import VueFormGenerator from 'vue-form-generator'
import 'vue-form-generator/dist/vfg.css'
// Form generator: NCForms: https://github.com/ncform/ncform
import vueNcform from '#ncform/ncform'
// eslint-disable-next-line no-unused-vars
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import ncformStdComps from '#ncform/ncform-theme-elementui'
// REST Calls: Axios: https://github.com/axios/axios
import axios from 'axios'
// Local files
import App from './App.vue'
import router from './router'
import store from './store'
import { i18n } from './localization'
import './antd'
import './registerServiceWorker'
// mocking api
import './services/axios/fakeApi'
Vue.use(BootstrapVue)
Vue.use(VueLayers)
Vue.use(NProgress)
Vue.use(VuePageTitle, {
prefix: 'Nedbank PhishTank | ',
router,
})
// Form generator: Vue-Form-Generator
Vue.use(VueFormGenerator)
// Form generator: NCForms
Vue.use(vueNcform, { extComponents: ncformStdComps, lang: 'en' })
window.$http = Vue.prototype.$http = axios
Vue.use(VueFormulate)
Vue.config.productionTip = false
const nprogress = new NProgress({ parent: 'body' })
new Vue({
router,
store,
nprogress,
i18n,
render: h => h(App),
}).$mount('#app')
My template looks like this:
<template>
<div>
<ncform :form-schema="formSchema" form-name="settings-form" v-model="item" #submit="submit()"></ncform>
<el-button #click="submit()">Submit</el-button>
</div>
</template>
<script>
export default {
data() {
return {
formSchema: {
type: 'object',
properties: {
name: {
type: 'string',
},
},
},
item: {
name: 'Peter Pan',
},
}
},
methods: {
submit () {
this.$ncformValidate('settings-form').then(data => {
if (data.result) {
console.log(this.$data.formSchema.value)
// do what you like to do
alert('finally!!!')
}
})
},
},
}
</script>
The error is:
Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
Am I missing something like registering the individual components? I thought this line would take care of it: Vue.use(vueNcform, { extComponents: ncformStdComps, lang: 'en' })
It feels like I should put something into the "new Vue()" statement - but I'm not sure what....
In main.js, you need to specify: Vue.use(Element);

Vue custom element error with vee-validate ValidationObserver component

I'm trying to use vee-validate to validate some inputs on this app. When trying to use the ValidationObserver custom tag I am getting this error.
[Vue warn]: Unknown custom element: <ValidationObserver> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
I add it to the components in the <script> section of the .vue element.
<script>
import { ValidationObserver } from 'vee-validate';
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
data: () => ({
name: 'ValidationObserver',
components: {
ValidationObserver,
},
// code continues on from here
In case it was necessary, I also included it in the components in my main.js file where the Vue app is created. It did not fix the error.
the components option should be outside the data option :
export default {
data: () => ({
name: 'ValidationObserver',
}),
components: {
ValidationObserver,
},

globally accessing const variables from a Vuex store

I have a very simple VueJS example I'm having some trouble with.
I have a js file called enums.js with the following line in it
export const modeEnumeration = { PLAYBACK: 'playback', RECORDING: 'recording', NONE: 'none' };
I'd like to set the initial value of a property in Vuex state to one of these modeEnumeration values. So this is my Vuex store.
import Vue from 'vue';
import Vuex from 'vuex';
import modeEnumeration from '../constants/enums';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
mode: modeEnumeration.NONE,
},
mutations: {
},
actions: {
},
modules: {
},
getters: {
},
});
However, I keep getting the following error in my Vuex store...
Uncaught TypeError: Cannot read property 'NONE' of undefined
What am I missing?
You export a named object, so you need to import it with curly braces:
import { modeEnumeration } from '../constants/enums';
The other solution would be to export a default:
export default { PLAYBACK: 'playback', RECORDING: 'recording', NONE: 'none' };

Problem to use VueI18n outside a component

I'm trying to use i18n outside a component I've found this solution https://github.com/dkfbasel/vuex-i18n/issues/16 telling to use Vue.i18n.translate('str'), but when I call this occurs an error Cannot read property 'translate' of undefined.
I'm using the following configuration
main.js
import i18n from './i18n/i18n';
new Vue({
router,
store,
i18n: i18n,
render: h => h(App)
}).$mount('#app')
i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import i18nData from './i18nData'
Vue.use(VueI18n);
export default new VueI18n({
locale: 'en',
messages: i18nData,
});
i18nData.js
export default {
en: {
//my messages
}
}
Then I trying to use this
import Vue from 'vue';
Vue.i18n.translate('someMessage');
Can anyone help me?
To use i18n with Vue 3's composition API, but outside a component's setup(), you can access its translation API (such as the t function) on its global property.
E. g. in a file with unit-testable composition functions:
// i18n/index.js
import { createI18n } from 'vue-i18n'
import en from './en.json'
...
export default createI18n({
datetimeFormats: {en: {...}},
locale: 'en',
messages: { en }
})
// features/utils.js
//import { useI18n } from 'vue-i18n'
//const { t } = useI18n() // Uncaught SyntaxError: Must be called at the top of a `setup` function
import i18n from '../i18n'
const { t } = i18n.global
You should import i18n instead of Vue
import i18n from './i18n'
i18n.tc('someMessage')
You can use VueI18n outside components by importing i18n then, use "t" from i18n.global.
"t" doesn't need "$" and you can change Locale with i18n.global.locale.
import i18n from '../i18n';
const { t } = i18n.global;
i18n.global.locale = 'en-US'; // Change "Locale"
const data = {
name: t('name'), // "t" doesn't need "$"
description: t('description'), // "t" doesn't need "$"
};
I managed to make it work this way:
import router from '../router';
Translate a text:
let translatedMessage = router.app.$t('someMessage');
Get the current language:
let language = router.app.$i18n.locale;

Categories