I am not sure what the problem is. I am creating a Vue/Vuex pagination system that calls my api to get my list of projects. The page initially loads all the projects in when the page is mounted. The Vuex does the inital call with axios. Vuex finds the projects and the number of pages. Once the user clicks on the pagination that is created with the pagination component, it should automatically change the projects for page 2...3 etc.
The problem I have is that it is not reactive until you press the page number twice. I am using vue 3. I have tried not using Vuex and that was successful. I am trying to create a single store that does all the axios calls. Thanks for all your help!
Vuex store
import { createStore } from 'vuex';
import axios from 'axios';
/**
* Vuex Store
*/
export const store = createStore({
state() {
return {
projects: [],
pagination: {}
}
},
getters: {
projects: state => {
return state.projects;
}
},
actions: {
async getProjects({ commit }, page = 1) {
await axios.get("http://127.0.0.1:8000/api/guest/projects?page=" + page)
.then(response => {
commit('SET_PROJECTS', response.data.data.data);
commit('SET_PAGINATION', {
current_page: response.data.data.pagination.current_page,
first_page_url: response.data.data.pagination.first_page_url,
prev_page_url: response.data.data.pagination.prev_page_url,
next_page_url: response.data.data.pagination.next_page_url,
last_page_url: response.data.data.pagination.last_page_url,
last_page: response.data.data.pagination.last_page,
per_page: response.data.data.pagination.per_page,
total: response.data.data.pagination.total,
path: response.data.data.pagination.path
});
})
.catch((e) => {
console.log(e);
});
}
},
mutations: {
SET_PROJECTS(state, projects) {
state.projects = projects;
},
SET_PAGINATION(state, pagination) {
state.pagination = pagination;
}
},
});
Portfolio Component
<template>
<div>
<div id="portfolio">
<div class="container-fluid mt-5">
<ProjectNav></ProjectNav>
<div class="d-flex flex-wrap overflow-auto justify-content-center mt-5">
<div v-for="project in projects" :key="project.id" class="m-2">
<Project :project="project"></Project>
</div>
</div>
</div>
</div>
<PaginationComponent
:totalPages="totalPages"
#clicked="fetchData"
></PaginationComponent>
</div>
</template>
<script>
import Project from "../projects/Project.vue";
import PaginationComponent from "../pagination/PaginationComponent.vue";
import ProjectNav from "../projectNav/ProjectNav.vue";
/**
* PortfolioComponent is where all the projects are displayed.
*/
export default {
name: "PortfolioComponent",
data() {
return {
location: "portfolio",
projects: []
};
},
components: {
Project,
PaginationComponent,
ProjectNav,
},
mounted() {
this.fetchData(1);
},
computed: {
totalPages() {
return this.$store.state.pagination.last_page;
},
},
methods: {
fetchData(page) {
this.$store.dispatch("getProjects", page);
this.projects = this.$store.getters.projects;
},
},
};
</script>
In your fetchData method you are calling the async action getProjects, but you are not waiting until the returned promise is resolved.
Try to use async and await in your fetchData method.
methods: {
async fetchData(page) {
await this.$store.dispatch("getProjects", page);
this.projects = this.$store.getters.projects;
},
},
Related
I want to fetch data everytime when props changes in component and display it without reloading page.
pages/invoice/index.vue:
<template>
<div>
<b-table-column
field="InvoiceNo"
label="Invoice No"
sortable
v-slot="props"
>
<a #click="selectInvoice(props.row.id)">
{{ props.row.invoiceNumber }}
</a>
</b-table-column>
<Invoice :invoiceId="selectedInvoice" />
</div>
</template>
<script>
import axios from "axios";
import Invoice from "../../../components/Invoice.vue";
export default {
components: {
Invoice,
},
data() {
return {
selectedInvoice: "",
}
},
methods: {
selectInvoice(invoiceId) {
this.selectedInvoice = invoiceId;
},
}
}
</script>
components/Invoice.vue:
<script>
import axios from "axios";
export default {
props: ["invoiceId"],
data() {
return {
invoiceData: "",
};
},
watch: {
invoiceId: function (newVal, oldVal) {
this.fetchData(newVal)
},
deep: true,
immediate: true,
},
methods: {
async fetchData(invoiceId) {
let { data: invoiceDetails } = await axios.get(
`${process.env.backendapi}/invoice/byid?invoiceId=${invoiceId}`
);
return {
invoiceData: invoiceDetails,
};
},
},
};
</script>
When I select/change invoice, I can see the backend api getting called everytime with selected invoice, but invoiceData is always blank. The returned result is not getting updated in invoiceData.
I think you want the following in the fetchData method
this.invoiceData = invoiceDetails
Instead of
return {}
Only the already existing data and fetch vue/nuxt functions need to return an object
I have a vue application on the frontend and a wordpress api on the backend. I am hitting the menus api and dynamically adding routes to the frontend at run time.
This works great. Until I reset the page on one of the dynamic routes. The component does not load and mounted() is never called. At this point, I can click the router link in the nav bar and the page component renders as expected.
For example. In the wordpress admin, I create a page called hello-world and add it to the primary menu. Vue will hit the api and create a route with the same name. I then load up the page and it loads fine. I click the hello world link in the nav bar, and it renders beautifully.
Now, I'm sitting at http://website.com/hello-world, and I reset the page. The app mounts and the nav bar renders. However, the page component does not render. If I click the link in the nav bar again, then it renders fine.
I am thinking this is a reactivity problem, but I can't find it. Any suggestions?
Edit. Been pondering this. The router component is loaded, and fetches the menu items asynchronously. Now, Im already sitting on one of the dynamic routes, /hello-world. The app is now loaded and there doesn't exist yet a hello-world route, since the api request is still pending. Since there is no matching route, the vue application doesn't know which component to mount... Perhaps there is a way to make the router component itself reactive?
relevant router code...
store.dispatch("getPrimaryMenu").then(() => {
store.state.menu.items.forEach((item) => {
if (item.object === "post") {
router.addRoute({
path: `/${item.slug}`,
name: item.slug,
component: () => import("#/views/Post.vue"),
});
}
if (item.object === "page") {
router.addRoute({
path: `/${item.slug}`,
name: item.slug,
component: () => import("#/views/Page.vue"),
});
}
});
});
and my store...
export default createStore({
state: {
menu: {
items: [],
},
page: {
title: {},
content: {},
},
post: {
title: {},
content: {},
},
},
mutations: {
SET_MENU(state, data) {
state.menu = data
},
SET_PAGE(state, data) {
state.page = data
},
SET_POST(state, data) {
state.post = data
},
},
actions: {
getPrimaryMenu({ commit, state }) {
console.log('get menus')
return new Promise(async (resolve, reject) => {
try {
const { data } = await axios.get(
`http://sslchkr.com/wp-json/menus/v1/menus/primary`, {
headers: {
'Content-Type': 'application/json'
}
}
)
commit('SET_MENU', data)
resolve(data)
} catch (e) {
reject(e)
}
})
},
getPage({ commit, state }, payload) {
console.log('get page')
return new Promise(async (resolve, reject) => {
try {
const { data } = await axios.get(
`http://sslchkr.com/wp-json/wp/v2/pages/${payload.id}`, {
headers: {
'Content-Type': 'application/json'
}
}
)
commit('SET_PAGE', data)
resolve(data)
} catch (e) {
reject(e)
}
})
},
getPost({ commit, state }, payload) {
console.log('get post')
return new Promise(async (resolve, reject) => {
try {
const { data } = await axios.get(
`http://sslchkr.com/wp-json/wp/v2/posts/${payload.id}`, {
headers: {
'Content-Type': 'application/json'
}
}
)
commit('SET_POST', data)
resolve(data)
} catch (e) {
reject(e)
}
})
},
},
}
a page component...
I am matching the route name to an item slug from the menu object, and using that item object_id to fetch the page object.
<template>
<div class="page">
<div>
<h1>{{ page.title.rendered }}</h1>
</div>
<div v-html="page.content.rendered"></div>
</div>
</template>
<script>
export default {
name: "Page",
computed: {
menuItem() {
return this.$store.state.menu.items.find(
(item) => item.slug === this.$route.name
);
},
page() {
return this.$store.state.page;
},
},
mounted() {
this.$store.dispatch("getPage", { id: this.menuItem.object_id });
},
};
</script>
and the nav component for completeness...
<template>
<ul id="menu-primary list-inline">
<li
v-for="item in menu.items"
:key="item.ID"
class="nav-item list-inline-item"
>
<router-link :to="slash(item.slug)" class="nav-link">{{
item.title
}}</router-link>
</li>
</ul>
</template>
<script>
export default {
name: "Nav",
computed: {
menu() {
return this.$store.state.menu;
},
},
methods: {
slash(s) {
return `/${s}`;
},
},
};
</script>
Edit to include main.js and App.vue
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.js'
import 'vue-toastification/dist/index.css'
import { createApp } from 'vue'
import Toast, { POSITION } from 'vue-toastification'
import App from './App.vue'
import router from './router'
import store from './store'
let app = createApp(App)
app.use(store)
app.use(router)
app.use(Toast, { position: POSITION.TOP_CENTER })
app.mount('#app')
<template>
<link rel="stylesheet" :href="theme" />
<Nav />
<div class="container-fluid">
<div class="row padding-top">
<div class="col-md-2"></div>
<div class="col-md-8">
<router-view :key="$route.path" />
</div>
<div class="col-md-2"></div>
</div>
</div>
</template>
<script>
import Nav from "#/components/Nav.vue";
export default {
components: {
Nav,
},
computed: {
theme() {
return this.$store.state.theme;
},
},
mounted() {
this.$store.dispatch("getTheme");
},
};
</script>
The problem I need to solve: I am writing a little vue-app based on VueJS3.
I got a lot of different sidebars and I need to prevent the case that more than one sidebar is open at the very same time.
To archive this I am following this article.
Now I got a problem:
Vue received a Component which was made a reactive object. This can lead to unnecessary performance overhead, and should be avoided by marking the component with markRaw or using shallowRef instead of ref. (6)
This is my code:
SlideOvers.vue
<template>
<component :is="component" :component="component" v-if="open"/>
</template>
<script>
export default {
name: 'SlideOvers',
computed: {
component() {
return this.$store.state.slideovers.sidebarComponent
},
open () {
return this.$store.state.slideovers.sidebarOpen
},
},
}
</script>
UserSlideOver.vue
<template>
<div>test</div>
</template>
<script>
export default {
name: 'UserSlideOver',
components: {},
computed: {
open () {
return this.$store.state.slideovers.sidebarOpen
},
component () {
return this.$store.state.slideovers.sidebarComponent
}
},
}
</script>
slideovers.js (vuex-store)
import * as types from '../mutation-types'
const state = {
sidebarOpen: false,
sidebarComponent: null
}
const getters = {
sidebarOpen: state => state.sidebarOpen,
sidebarComponent: state => state.sidebarComponent
}
const actions = {
toggleSidebar ({commit, state}, component) {
commit (types.TOGGLE_SIDEBAR)
commit (types.SET_SIDEBAR_COMPONENT, component)
},
closeSidebar ({commit, state}, component) {
commit (types.CLOSE_SIDEBAR)
commit (types.SET_SIDEBAR_COMPONENT, component)
}
}
const mutations = {
[types.TOGGLE_SIDEBAR] (state) {
state.sidebarOpen = !state.sidebarOpen
},
[types.CLOSE_SIDEBAR] (state) {
state.sidebarOpen = false
},
[types.SET_SIDEBAR_COMPONENT] (state, component) {
state.sidebarComponent = component
}
}
export default {
state,
getters,
actions,
mutations
}
App.vue
<template>
<SlideOvers/>
<router-view ref="routerView"/>
</template>
<script>
import SlideOvers from "./SlideOvers";
export default {
name: 'app',
components: {SlideOvers},
};
</script>
And this is how I try to toggle one slideover:
<template>
<router-link
v-slot="{ href, navigate }"
to="/">
<a :href="href"
#click="$store.dispatch ('toggleSidebar', userslideover)">
Test
</a>
</router-link>
</template>
<script>
import {defineAsyncComponent} from "vue";
export default {
components: {
},
data() {
return {
userslideover: defineAsyncComponent(() =>
import('../../UserSlideOver')
),
};
},
};
</script>
Following the recommendation of the warning, use markRaw on the value of usersslideover to resolve the warning:
export default {
data() {
return {
userslideover: markRaw(defineAsyncComponent(() => import('../../UserSlideOver.vue') )),
}
}
}
demo
You can use Object.freeze to get rid of the warning.
If you only use shallowRef f.e., the component will only be mounted once and is not usable in a dynamic component.
<script setup>
import InputField from "src/core/components/InputField.vue";
const inputField = Object.freeze(InputField);
const reactiveComponent = ref(undefined);
setTimeout(function() => {
reactiveComponent.value = inputField;
}, 5000);
setTimeout(function() => {
reactiveComponent.value = undefined;
}, 5000);
setTimeout(function() => {
reactiveComponent.value = inputField;
}, 5000);
</script>
<template>
<component :is="reactiveComponent" />
</template>
I have an action in Vuex actions which commit a mutation that it take a payload from the component, that is a number of the index for returning an object, it works fine on Vuex js file meaning that shows the selected item on the console, as I said it gets index from the payload,
but on the component, it gives me Promise <Pending>, why that's happening? for now, I do not use any API for my Nuxt/Vue app, but I will, and for now, I just want to know why this is happening and what is the best solution for solving this
Here my Vuex codes:
export const state = () => ({
articles: [
{
uid: 0,
img: 'https://raw.githubusercontent.com/muhammederdem/mini-player/master/img/1.jpg',
link: '/articles/1',
},
{
uid: 1,
img: 'https://raw.githubusercontent.com/muhammederdem/mini-player/master/img/2.jpg',
link: '/articles/2',
},
],
})
export const getters = {
getArticles(state) {
return state.articles
},
}
export const mutations = {
getSpeceficArticle(state, payload) {
return state.articles[payload]
},
}
export const actions = {
getSpeceficArticle({ commit }, payload) {
commit('getSpeceficArticle', payload)
},
}
and here my component codes:
<template>
<div class="article">
{{ getSpeceficArticle() }}
<div class="article__banner">
<img src="" alt="" />
</div>
<div class="article__text">
<p></p>
</div>
</div>
</template>
<script>
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
// computed: {},
methods: {
async getSpeceficArticle() {
return await this.$store.dispatch('articles/getSpeceficArticle', 0)
},
},
}
</script>
actions are used to update the state they are like mutations but the main difference between them is that actions can include some asynchronous tasks, if you want to get a specific article at given index you should use a getter named getArticleByIndex :
export const getters = {
getArticles(state) {
return state.articles
},
getArticleByIndex:: (state) => (index) => {
return state.articles[index]
}
}
then define a computed property called articleByIndex :
<script>
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
computed: {
articleByIndex(){
return this.$store.getters.articles.getArticleByIndex(0)
}
},
methods: {
},
}
</script>
#Mohammad if you find yourself using a lot of getters/actions etc from Vuex and they're starting to get a little wordy, you can bring in mapGetters from Vuex and rename your calls to something a little more convenient. So your script would become,
<script>
import { mapGetters } from 'vuex'
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
computed: {
articleByIndex(){
return this.getArticleByIndex(0)
}
},
methods: {
...mapGetters({
getArticleByIndex: 'articles/getArticleByIndex',
})
},
}
</script>
You can add ...mapGetters, ...mapActions to your computed section also.
since there is no web service call in vuex action, try to remove async and await keywords from the component.
Later when you add a webservice call than you can wrap action body in new Promise with resolve and reject and then you can use async and await in component. let me know if this works for you.
I am new to vue js and have been trying for hours to get airtable data into my application. I am hoping someone could help me as I feel I am almost there! I am using the Airtable NPM package to retrieve the data - https://www.npmjs.com/package/airtable
<template>
<section id="cards-section" class="cards-section">
<div class="centered-container w-container">
<h1>{{ msg }}</h1>
<div class="cards-grid-container">
<Card />
<ul id="example-1">
<li v-for="item in recordsList" v-bind:key="item">
data here {{ item }}
</li>
</ul>
</div>
</div>
</section>
</template>
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",
components: {
Card,
},
props: {
msg: String,
},
data() {
return {
recordsList: [],
};
},
mounted() {
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",
})
.firstPage(function (err, records) {
if (err) {
console.error(err);
return;
}
records.forEach( (record) => {
console.log(record.get("Name"));
return record.get("Name")
});
});
},
};
</script>
<style scoped>
</style>
Looking at your code you are probably at the stage that you have succesfully retrieved the data from airtable and seeing some records in your console.log.
Now how to get them from inside that function to your Vue instance:
I will show you two ways to go about this and explain them later:
Method 1: Using a reference to self.
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",
components: {
Card,
},
props: {
msg: String,
},
data() {
return {
recordsList: [],
};
},
mounted() {
// create a reference to this vue instance here.
var self = this;
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",
})
.firstPage(function (err, records) {
if (err) {
console.error(err);
return;
}
// now we can set the recordList of our
// vue instance:
self.recordsList = records;
});
},
};
</script>
Method 2: Using javascript arrow function:
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",
components: {
Card,
},
props: {
msg: String,
},
data() {
return {
recordsList: [],
};
},
mounted() {
// no need to create a reference this time.
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",
})
.firstPage( (err, records) => {
if (err) {
console.error(err);
return;
}
this.recordsList = records;
});
},
};
</script>
Now what was the problem? In the first example we use a normal javascript anonymous function. this inside a normal javascript anonymous function is not what you expect it to be. We solve this by defining a reference to this (var self = this) somewhere and instead of trying this.recordsList we do self.recordsList inside our anynomous function.
Nem improvements to the javascript language introduced another type of function, the arrow function. One benefit of this function is that this inside this function is the object that you've defined it in. So, this is our vue instance. Now we don't have a problem and can just set this.recordsList.
Other solutions i've ommitted are:
Using Function.bind
async/await