I'm a little confused. How to load data (main.js file) and afrer (inside a component) set this data to data() function (calc.js)?
I have the data.json file:
{
"store_data": "VUE_STORE",
}
I have the store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
url_server: 'data.json',
store_data: '',
},
actions: {
getServerData({commit}){
return new Promise((resolve, reject) => {
Vue.http.get(this.state.url_server).then(function (response) {
if (response.status == "200") {
commit('LOAD_SERVER_DATA', response)
resolve()
}
});
});
}
},
mutations: {
LOAD_SERVER_DATA (state, response) {
this.store_data = response.data.store_data;
},
},
});
I have the main.js file:
import Vue from 'vue';
import VueResource from 'vue-resource';
import { store } from './store/store';
Vue.config.productionTip = false;
import calc from './components/calc/calc';
Vue.use(VueResource);
var app = new Vue({
el: '#app',
store,
data: {},
components: {
'calc': calc,
},
beforeCreate() {
this.$store.dispatch('getServerData');
}
});
And the component file calc.js
module.exports = {
name: 'calc',
template: `
<div>
<h1>calc</h1>
<h2>{{test_value}}</h2>
</div>
`,
data() {
return {
test_value: 'AAA',
}
},
methods: {
updateTimer() {
},
},
created() {
this.test_value = this.$store.state.store_data;
/* this.$store.dispatch('getServerData').then(() => {
this.test_value = this.$store.state.store_data;
console.log(this.$store.state.store_data);
});*/
},
computed: {
},
mounted() {
},
};
I'd like to set a test_value in calc.js file value this.$store.state.store_data. How it is possible?
Don't use data for data owned by the store. Use computed to return the store value, like so
created() {
this.$store.dispatch('getServerData');
},
computed: {
test_value(){
return this.$store.state.store_data;
}
},
mounted() {
},
And then in the vuex store the mutation has a little bug
mutations: {
LOAD_SERVER_DATA (state, response) {
state.store_data = response.data.store_data;
},
Related
I'm coding along with a Nuxt course and I got the following error while of course it worked in the tutorial.
TypeError: can't access property "dispatch", this.$store is undefined
store/index.js file:
import Vuex from "vuex";
const createStore = () => {
return new Vuex.Store({
state: { loadedPosts: [] },
mutations: {
setPosts(state, posts) {
state.loadedPosts = posts;
},
},
actions: {
setPosts(vuexContext, posts) {
vuexContext.commit("setPosts", posts);
},
},
getters: {
loadedPosts(state) {
console.log("imhere");
return state.loadedPosts;
},
},
});
};
export default createStore;
the script in posts/index.vue file:
<script>
export default {
data() {
return {
loadedPosts: [{id: "1",title: "First Post"}],
};
},
created() {
this.$store.dispatch("setPosts", this.loadedPosts);
},
};
</script>
I'm using vue 3 with composition api and vuex 4, I've done it this way before but now its throwing that error.
Here's my store/index.js
import { createStore } from "vuex";
export const store = new createStore({
state: {
patient: [],
},
mutations: {
setPatient(state, payload) {
state.patient = payload;
},
},
getters: {
getPatient(state) {
return state.patient;
},
getAppointment(state) {
return state.patient.appointments;
},
},
})
app.js
require('./bootstrap');
import { createApp, h } from 'vue';
import { createInertiaApp } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
import {store} from './Store'
const { RayPlugin } = require('vue-ray');
window.$ = window.jQuery = require("jquery");
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => require(`./Pages/${name}.vue`),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.use(store)
.use(RayPlugin, { interceptErrors: true, host: '127.0.0.1', port: 23517 })
.mixin({ methods: { route } })
.mount(el);
},
});
InertiaProgress.init({ color: '#4B5563' });
And following the documentation, on my component I did the following:
import { useStore } from 'vuex'
import {onMounted, reactive, ref} from "vue";
export default {
props: {
patient: {
type: Object,
required: true
}
},
setup(props) {
const store = useStore();
onMounted(() => {
store.commit('setPatient', props.patient);
})
}
}
So far I've done this before, but using the composition api is new for me, so I couldn't find where the error is
So basically I have this component and I am using its created hook to fetch data using vue-resource and VUEX action, storing that data in store and right after that trying to get that data using VUEX getter but I am unable to do so. Any work around or I am doing something wrong. I am new to Vue!
Component:
import { mapActions } from 'vuex';
import { mapGetters } from 'vuex';
export default {
components: {
categoryHeader: CategoryHeader,
categoryFooter: CategoryFooter,
AddCategory
},
data() {
return {
openCatAdd: false,
categories: [],
pagination: []
}
},
methods: {
...mapActions([
'getCategories'
]),
...mapGetters([
'allCategories'
])
},
created() {
this.getCategories(1);
this.categories = this.allCategories();
// console.log(this.categories);
}
};
Store:
import Vue from "vue";
const state = {
categories: [],
};
const mutations = {
setCategories: (state, payload) => {
state.categories = payload;
}
};
const actions = {
getCategories: ({commit}, payload) => {
Vue.http.get('categories?page='+payload)
.then(response => {
return response.json();
})
.then(data => {
commit('setCategories', data.data);
}, error => {
console.log(error);
})
}
}
const getters = {
allCategories: state => {
console.log(state.categories);
return state.categories;
}
};
export default {
state,
mutations,
actions,
getters
};
I am recieving "Critical dependency: require function is used in a way in which dependencies cannot be statically extracted friendly-errors 16:21:14" error when using the package scrollMonitor in my nuxt project
plugins/scroll-monitor.js
import Vue from 'vue';
// your imported custom plugin or in this scenario the 'vue-session' plugin
import ScrollMonitor from 'scrollmonitor';
Vue.use(ScrollMonitor);
nuxt.config.js
plugins: [
'~/plugins/wordpress-api',
{ src: '~/plugins/scroll-monitor.js', ssr: false }
],
build: {
/*
** You can extend webpack config here
*/
vendor: ['scrollmonitor'],
extend(config, ctx) {
}
}
At my index.vue file
let scrollmonitor
if (process.client) {
scrollmonitor = require('scrollmonitor')
}
More context
Still not working.
I am using new computer, at my old one everything is working fine.
index.vue
<template>
<div class="index page-padding-top">
<TheHero
:scaledUpDot="scaledUpDot"
:isFirstImageVisible="isFirstImageVisible"
/>
<ProjectsList :projects="projects" />
</div>
</template>
<script>
import { mapGetters } from "vuex";
import TheHero from "~/components/TheHero";
import ProjectsList from "~/components/ProjectsList";
export default {
async mounted () {
if (process.browser) {
const scrollMonitor = await import('scrollmonitor')
Vue.use(scrollMonitor)
console.log('HELLO FROM MOUNTED')
}
},
name: "Index",
components: { TheHero, ProjectsList},
data() {
return {
scaledUpDot: false,
isFirstImageVisible: false,
};
},
computed: {
...mapGetters({
projects: "getProjects",
}),
},
mounted() {
this.handleScaling();
this.hideScrollSpan();
},
destroyed() {
this.handleScaling();
this.hideScrollSpan();
},
methods: {
handleScaling() {
if (process.client) {
const heroSection = document.querySelectorAll(".hero");
const heroSectionWtcher = scrollMonitor.create(heroSection, 0);
heroSectionWtcher.enterViewport(() => {
this.scaledUpDot = true;
});
}
},
hideScrollSpan() {
if (process.client) {
const images = document.querySelectorAll(".projects-home img");
const firstImage = images[0];
const imageWatcher = scrollMonitor.create(firstImage, -30);
imageWatcher.enterViewport(() => {
this.isFirstImageVisible = true;
});
}
},
},
};
</script>
In my old computer I have it imported like this :
import { mapGetters } from 'vuex'
import scrollMonitor from 'scrollmonitor'
But when I want to run this in a new one I get an error that window is not defined
So I have started to add this plugin in other way and still not working
Still not working.
I am using new computer, at my old one everything is working fine.
index.vue
<template>
<div class="index page-padding-top">
<TheHero
:scaledUpDot="scaledUpDot"
:isFirstImageVisible="isFirstImageVisible"
/>
<ProjectsList :projects="projects" />
</div>
</template>
<script>
import { mapGetters } from "vuex";
import TheHero from "~/components/TheHero";
import ProjectsList from "~/components/ProjectsList";
export default {
async mounted () {
if (process.browser) {
const scrollMonitor = await import('scrollmonitor')
Vue.use(scrollMonitor)
console.log('HELLO FROM MOUNTED')
}
},
name: "Index",
components: { TheHero, ProjectsList},
data() {
return {
scaledUpDot: false,
isFirstImageVisible: false,
};
},
computed: {
...mapGetters({
projects: "getProjects",
}),
},
mounted() {
this.handleScaling();
this.hideScrollSpan();
},
destroyed() {
this.handleScaling();
this.hideScrollSpan();
},
methods: {
handleScaling() {
if (process.client) {
const heroSection = document.querySelectorAll(".hero");
const heroSectionWtcher = scrollMonitor.create(heroSection, 0);
heroSectionWtcher.enterViewport(() => {
this.scaledUpDot = true;
});
}
},
hideScrollSpan() {
if (process.client) {
const images = document.querySelectorAll(".projects-home img");
const firstImage = images[0];
const imageWatcher = scrollMonitor.create(firstImage, -30);
imageWatcher.enterViewport(() => {
this.isFirstImageVisible = true;
});
}
},
},
};
</script>
In my old computer I have it imported like this :
import { mapGetters } from 'vuex'
import scrollMonitor from 'scrollmonitor'
But when I want to run this in a new one I get an error that window is not defined
So I have started to add this plugin in other way and still not working
When I'm trying to use the "getProducts" method through mapActions i am getting the "this.getProducts" is not a function.
Basically i get the actions from my product.js. So i don't know really why the error is existing.
I hope u can help me to handle with it. :)
My component ProductList.vue:
<script>
import ProductCard from "./ProductCard.vue";
import { mapState, mapActions } from "vuex";
export default {
components: {
ProductCard
},
computed: {
//state.modulname.state.js(products state)
...mapState("product" ["products"])
},
mounted() {
this.getProducts();
},
methods: {
...mapActions("product"["getProducts"])
}
};
</script>
<style>
</style>
My product.js File:
import store from "../../store/store";
import Product from "../../apis/Product";
const state = {
product: null,
products: [],
};
const mutations = {
SET_PRODUCT(state, product) {
state.product = product;
},
SET_PRODUCTS(state, products) {
state.products = products;
},
};
const actions = {
getProduct({ commit }, productId) {
Product.show(productId).then((response) => {
commit("SET_PRODUCT", response.data);
});
},
getProducts({ commit }) {
Product.all().then((response) => {
commit("SET_PRODUCTS", response.data);
});
},
};
const getters = {
getProductID() {
return (id) => state.products.filter((product) => product.id === id);
},
};
export default {
namespaced: true,
store,
state,
mutations,
actions,
getters,
};
Try this:
...mapActions([
'product/getProducts'
])