I using vuetify : https://vuetifyjs.com/en/
I want to use moment.js. So I read this reference : https://www.npmjs.com/package/vue-moment
I had run npm install vue-moment
I'm still confused to put this script Vue.use(require('vue-moment'));
In the vuetify, there exist two file : main.js and index.js
main.js like this :
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/index'
import './registerServiceWorker'
import vuetify from './plugins/vuetify'
Vue.config.productionTip = false
new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount('#app')
index.js like this :
import Vue from 'vue';
import Vuex from 'vuex';
import dataStore from './modules/data-store';
import createLogger from "vuex/dist/logger";
Vue.use(Vuex);
const debug = process.env.VUE_APP_DEBUG !== "production";
export default new Vuex.Store({
modules: {
dataStore
},
strict: debug,
plugins: debug ? [createLogger()] : []
});
where do i put Vue.use(require('vue-moment'));?
I try to put it in the main.js, but if i call my vue component, there exist error : ReferenceError: moment is not defined
My vue component like this :
<template>
...
</template>
<script>
export default {
mounted() {
let a = moment("2012-02", "YYYY-MM").daysInMonth();
console.log(a)
}
};
</script>
I found this at the bottom of the vue-moment npm page
vue-moment attaches the momentjs instance to your Vue app as
this.$moment.
This allows you to call the static methods momentjs provides.
So you should be able to use your original configuration of vue-moment and do this in your mounted() method
mounted() {
let a = this.$moment("2012-02", "YYYY-MM").daysInMonth();
console.log(a)
}
notice this.$moment
And for the set up of vue-moment you should place this in your main.js file
main.js
Vue.use(require('vue-moment'))
=========================================================================
GLOBAL
If you want to use moment with Vue globally you can create an Instance Proprety
main.js
import moment from 'moment'
Vue.prototype.moment = moment
In your component you then call this.moment in your methods or computed properties. In your mounted section it would look like this
mounted() {
let a = this.moment("2012-02", "YYYY-MM").daysInMonth();
console.log(a)
}
COMPONENT
If you just want to use moment in a component you can include directly like this
<script>
import moment from 'moment'
export default {
mounted(){
let a = moment("2012-02", "YYYY-MM").daysInMonth();
console.log(a)
}
}
</script>
Related
I am using vue 2.6.14 and composition-api 1.3.3 package to use composition api. I have
my main.js like
import Vue from 'vue'
import VueCompositionAPI from '#vue/composition-api'
Vue.use(VueCompositionAPI)
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
I try to setup a store
I have a src folder / store folder / index.js
and inside the index.js
import { reactive } from '#vue/composition-api'
const state = reactive({
counter : 0
})
export default{ state }
inside App.vue I try to import store to use it
<script>
import store from '#/store'
</script>
I get the error Uncaught Error: [vue-composition-api] must call Vue.use(VueCompositionAPI) before using any function.
I tried all solutions from here and nothing works. If I remove the import store from '#/store' the error goes away. Using vue 3 s not an option.
How can I solve this?
Thanks
imports are automatically hoisted to the top of the file, so it actually precedes the Vue.use(VueCompositionApi) at runtime.
So these lines:
import Vue from 'vue'
import VueCompositionAPI from '#vue/composition-api'
Vue.use(VueCompositionAPI)
import App from './App.vue' 👈 hoisted
...become:
import Vue from 'vue'
import VueCompositionAPI from '#vue/composition-api'
import App from './App.vue' 👈
Vue.use(VueCompositionAPI)
So the plugin doesn't get installed before App.vue gets imported, leading to the error you observed.
Option 1: Move plugin installation to own file
You can move the installation of #vue/composition-api into its own file that could be imported before App.vue:
// lib/composition-api.js
import Vue from 'vue'
import VueCompositionAPI from '#vue/composition-api'
Vue.use(VueCompositionAPI)
// main.js
import Vue from 'vue'
import './lib/composition-api'
import App from 'App.vue'
demo 1
Option 2: Use require() in App.vue
require the store in the component's setup(), where the #vue/composition-api would've already been installed:
// App.vue
import { defineComponent, computed } from '#vue/composition-api'
export default defineComponent({
setup() {
const store = require('#/store').default
return {
counter: computed(() => store.state.counter),
increment: () => store.state.counter++,
}
},
})
demo 2
Option 3: Use import() in App.vue
Dynamically import the store with import(). This is especially needed in Vite, which does not have require().
// App.vue
import { defineComponent, computed, ref } from '#vue/composition-api'
export default defineComponent({
setup() {
const store = ref()
import('#/store').then(mod => store.value = mod.default)
return {
counter: computed(() => store.value?.state.counter),
increment: () => store.value && store.value.state.counter++,
}
},
})
demo 3
I'm building a web component using the following command :
vue-cli-service build --target wc --name my-element 'src/components/mycomponent.vue'
I would like to use Vuetify inside of this component. How do I add it to mycomponent.vue so that it is scoped inside the component's shadow root?
This component will be dynamically loaded into apps built with other frameworks/styles. I want the web component to be able to use, for example, v-btn, v-layout, etc. within it.
Thank you,
Donnie
For vuetify 2.x, it requires initialization on Vue instance as follows.
// plugins/vuetify.js
import Vue from 'vue'
import Vuetify from 'vuetify/lib'
Vue.use(Vuetify);
const opts = {};
export default new Vuetify(opts);
// main.js
import Vue from 'vue';
import App from './app.vue';
import vuetify from './plugins/vuetify';
new Vue({
vuetify,
render: h => h(App),
}).$mount('#app');
You need to move such initialization into your web component instead.
<template>
...
</template>
<script>
import { VBtn, VLayout } from 'vuetify/lib'
import vuetify from '../plugins/vuetify';
export default {
name: 'MyWebComponent',
vuetify,
components: {
VBtn,
VLayout
},
...
}
</script>
<style>
...
</style>
From v1.3, you can import individual components, A La Carte...
<template>
<!-- whatever -->
</template>
<script>
import { VBtn, VLayout } from 'vuetify/lib'
export default {
name: 'MyElement',
components {
VBtn,
VLayout
},
// etc
}
</script>
See https://vuetifyjs.com/en/framework/a-la-carte#importing-components
When I invoke an imported vuex action in my vue file the code errors out and breaks the site. I've even broken it down to the simplest of things (console log a string from within the action when I click a button tied to that action).
In my Vue root
import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import JsonCSV from 'vue-json-csv'
import { store } from './store/index'
Vue.component('downloadCsv', JsonCSV)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router,
store
}).$mount('#app')
In my .vue file:
import {mapGetters,mapActions} from 'vuex'
methods: {
...mapActions([
'sendDraftSelectionPost'
]),
selectPlayerMethod() {
this.sendDraftSelectionPost('hello')
}
}
In my index.js file in which I've imported Vuex
import Vue from 'vue'
import Vuex from 'vuex'
import { debug } from 'util';
import draft from './modules/draft'
Vue.use(Vuex)
Vue.config.devtools = true
const store = new Vuex.Store({
strict: debug,
modules: {
draft,
}
})
export default store
In my actions.js file:
const actions = {
sendDraftSelectionPost ({ commit }, draftSelection) {
console.log(draftSelection)
}
}
export default actions
The expected results should be I simply see a string console logged in dev console saying 'Hello'
However, I get a bit nasty error saying the following:
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'dispatch' of undefined"
I haven't even typed the word "dispatch" in my code, so I'm thoroughly confused. After searching on here and finding a lot of posts similar, I haven't found anything that has a solid answer or solution.
Any help is appreciated.
Per conversation with #Phil, the solution to the original problem (not the sub problem stated in the comments) was to fix my import in my root Vue from import { store } from './store/index' to import store from './store'. Thanks, #Phil!!!
So I am totally new to vuex. I carefully install the vuex to my vue app but I can't acess the this.$store in any of my child component.
I have also read more than 10 questions ask the same thing and I did a lot of changes, tried lots of times. Since I thought I did everything right and it still doesn't work. I finally decide to come here and ask. I will put my own codes below:
file structure (only related files):
|---main.js
|---store.js
|---App.vue
|---components
main.js:
import '#babel/polyfill'
import Vue from 'vue'
import App from './App.vue'
import './plugins/vuetify'
import './plugins/vue-resource'
import { store } from './store';
require('../node_modules/ol/ol.css');
Vue.config.productionTip = false
fetch('static/App_Config.json')
.then(function (response) {
return response.json().then(function (AppConfig) {
Vue.prototype.$AppConfig = AppConfig;
new Vue({
store,
render: h => h(App)
}).$mount('#app')
});
})
store.js:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex, {
});
export const store = new Vuex.Store({
state: {
testText: "test string"
}
});
in components: (simplified, only related codes)
<script>
created () {
console.log("this.$store_test: ", this.$store);
}
</script>
I have already tried these possibilties:
in main.js:
use import store from './store'; rather than import { store } from './store';
in main.js:
use store: store, rather than store,
in store.js:
use Vue.use(Vuex); rather than Vue.use(Vuex, {});
in store.js: (combined with 1. I have tried all 4 combinitions)
use export default store = new Vuex.Store rather than export const store = new Vuex.Store
put the console not in created hook, but in methods, and made a button to trigger it.
put the console in other child components, which nested in different deeps
After I serched a lot similar qustions and tried a lot (also with 20+ time server restart). I still can get this.$store. I kind of need some help.
I DO NOT think this question is duplicate, because I have already read other questions and tried all the possiblities. If they all failed, it must be something new here with mine codes.
This is a valid Vuex store.js file:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
testText: "test string";
}
});
export default store;
Remember to create a getter, mutation and action for your variables in Vuex, you should not handle the state directly.
It doesn't matter in main.js if you use store or store: store, they are identical.
import store from './store' is the same as import { store } from './store'.
Vue.use(Vuex) and Vue.use(Vuex, {}) are the same as long as you don't supply any options.
You don't need to get the store in a component somewhere, you're loading Vuex before the app is mounted, so you can actually start using it in e.g. the main.js created hook.
Your components <script> tag is incorrect. You should use export default, like this:
<script>
export default {
created () {
// Check if console.log like this works better as well
console.log("Store test:");
console.log(this.$store);
}
}
</script>
I am using Vuejs with Webpack.
Here's store.js:
import Vuex from "vuex";
export default new Vuex.Store({
state: {
count : 0
},
mutations: {
increment (state) {
state.count++
}
}
});
Here is my app.js:
"use strict";
import Vue from 'vue';
window.Vue = Vue;
import MyComponent from './MyComponent.vue';
import store from './store.js';
window.App = new Vue({
el : '#my-app',
store,
components : {
'my-component' : MyComponent
}
});
Here is the script from MyComponent.vue:
export default {
computed : {
count() {
return this.$store.state.count;
}
},
mounted() {
console.log(this.$store)
}
}
Any reference to this.$store in my component is undefined. Why?
You need to install the Vuex plugin somewhere to allow Vue components to access the store. As Pavan noted, to do this you must include the following lines somewhere (in your app's index.js, in your store.js etc) before you create your Vue instance:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
This tells Vue what to do with the store instance when you create the instance, which will make it available under this.$store in your components. This also ensures that Vuex also knows how to interact with Vue. Without it, you will not be able to use Vue and Vuex together properly.
Regarding your later answer, you can export the store instance just fine, and import it into your index.js, router config etc. For example:
store.js:
import Vuex from "Vuex";
export default new Vuex.Store({ /* store config */ });
MyComponent.vue's <script> block:
export default {
mounted() {
console.log(this.$store); // will log the store instance
}
}
index.js:
import Vue from "vue";
import Vuex from "vuex";
import store from "./store";
import MyComponent from "./components/MyComponent.vue";
Vue.use(Vuex);
const app = new Vue({
el: "#my-app"
store,
components: { MyComponent },
// any other options as needed
});
You should add these 2 lines in your store.js
import Vue from "vue";
Vue.use(Vuex);
There's no way you can instantiate store without actually saying the second statement above. So, you need to import Vue in your store.js
OK, so the reason I wanted to go down this path was to separate the store code from the rest of the application.
I have managed to do that by exporting a default object from store.js, where that object is only the configuration for the store (i.e. not a store instance). I then instantiate the store in my app.js, using the imported configuration.
I will leave this answer open for a few days in case someone wants to provide a way to export/import the instance itself.