HelloWorld.vue
import axios from "axios";
export const router = () => axios.get("https://fakestoreapi.com/products");
<template>
<div>
<div v-for="item in items" :key="item.id">
<b> id: {{ item.id }}</b>
<router-link
:to="`/${item.id}`"
>
{{ item.title }}
</router-link>
</div><!-- end v-for -->
<router-view></router-view>
</div>
</template>
<script>
import { router } from "./router";
export default {
name: "HelloWorld",
components: {},
data() {
return {
items: [],
};
},
mounted() {
router().then((r) => {
this.items = r.data;
});
},
};
</script>
User.vue
import axios from "axios";
export const routerid = (itemId) =>
axios.get("https://fakestoreapi.com/products/" + itemId);
<template>
<div>
<div v-if="item">
<h1>Price: {{ item.price }}</h1>
</div>
<tabs />
</div>
</template>
<script>
import { routerid } from "./routerid";
import tabs from "./tabs";
export default {
name: "User",
components: {
tabs,
},
data() {
return {
item: null,
};
},
mounted() {
this.loadData();
},
computed: {
routeId() {
return this.$route.params.id;
},
},
watch: {
routeId() {
console.log("Reload (route change)");
this.loadData();
}, //reload when route id changes
},
methods: {
loadData() {
console.log("Reloading, ID", this.routeId);
if (!this.routeId) return; // no ID, leave early
routerid(this.$route.params.id).then((item) => {
this.item = item.data;
});
},
},
};
</script>
tabs.vue
import axios from "axios";
export const tabsandcontent = async (itemId) =>
await axios.get("https://fakestoreapi.com/products?limit=" + itemId);
<template>
<div>
<div v-if="item">
<h1>description: {{ item.description }}</h1>
</div>
</div>
</template>
<script>
import { tabsandcontent } from "./tabsandcontent";
export default {
name: "User",
components: {},
data() {
return {
item: null,
};
},
mounted() {
this.loadData();
},
computed: {
tabsandcontent() {
return this.$route.params.id;
},
},
watch: {
tabsandcontent() {
console.log("Reload (route change)");
this.loadData();
}, //reload when route id changes
},
methods: {
loadData() {
console.log("Reloading, ID", this.tabsandcontent);
if (!this.tabsandcontent) return; // no ID, leave early
tabsandcontent(this.$route.params.id).then((item) => {
this.item = item.data;
});
},
},
};
</script>
main.js
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld";
import User from "./components/User";
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{
path: "/HelloWorld",
name: "HelloWorld",
component: HelloWorld,
children: [{ path: ":id", name: "User", component: User }]
}
]
});
Vue.config.productionTip = false;
new Vue({
router,
render: (h) => h(App)
}).$mount("#app");
code:- https://codesandbox.io/s/combined-logic-api-forked-41lh0f?file=/src/main.js
can you please answer this, In main.js routing I changed from path: "/" to path: "/HelloWorld" then all of sudden output not reflecting... because in my project path:'/' indicates login page??? In this scenario what changes, i need to make, to make logic work
also where is the relation between path:'/' and api call??
You have same name for the variables in tabs component (In watch and computed). And In tabsandcontent.js, you have missed to fetch description for the specific item as performed in routerId.js.
Have a look at modified version which is working as you expected.
https://codesandbox.io/embed/combined-logic-api-forked-ji5oh4?fontsize=14&hidenavigation=1&theme=dark
First thing first, I want you to know that I don't understand what are you asking for. But I'm going to try to answer.
Your first question:
In main.js routing I changed from path: "/" to path: "/HelloWorld" then all of sudden output not reflecting.
Yes, you will not see your HelloWorld.vue component. You can see your page however if you type <your-url>/HelloWorld. Usually the / path is used for something like "Home" page.
However, I've tried checking out your codesandbox. And take a look at your HelloWorld.vue component.
I think you are confused because when you changed the path from / to /HelloWorld apart from the HelloWorld.vue not showing up. It somehow broken the link which causes the API in tabs.vue not functioning.
If that's the case, you just have to simply add HelloWorld/${item.id} in tabs.vue,
<template>
<div>
<div v-for="item in items" :key="item.id">
<b> id: {{ item.id }}</b>
<router-link
:to="`HelloWorld/${item.id}`" // --> Notice this line
>
{{ item.title }}
</router-link>
</div><!-- end v-for -->
<router-view></router-view>
</div>
</template>
This however, isn't a common thing to do routing. You should add your App URLs to main.js. Which also isn't common, but I'm assuming this is just a little reproduction code you made for StackOverflow.
Here are my CodeSandbox edits.
https://codesandbox.io/s/combined-logic-api-forked-jttt8p
I will update the answer again later, I'm still not on my personal laptop.
Related
HelloWorld.vue
<template>
<div>
<b>Vuejs dynamic routing</b>
<div v-for="item in items" :key="item.id">
<b>{{ item.id }}.</b>
<router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
{{ item.kk }}
</router-link>
<router-link name="twoval"></router-link>
</div>
<br /><br /><br />
<User />
<Usertwo />
</div>
</template>
<script>
import User from "./User.vue";
import Usertwo from "./Usertwo.vue";
import { datalist } from "./datalist";
export default {
name: "HelloWorld",
components: {
User,
Usertwo,
},
data() {
return {
items: datalist,
};
},
};
</script>
User.vue
<template>
<div>
<div v-for="(item, key) in user" :key="key">
{{ item }}
</div>
</div>
</template>
<script>
import { datalist } from "./datalist";
export default {
name: "User",
data() {
return {
lists: datalist,
};
},
computed: {
user: function () {
return this.lists.find((item) => item.id === this.$route.params.id);
},
},
};
</script>
Usertwo.vue
<template>
<div>
<div v-for="usertwo in usertwos" :key="usertwo.mid">
{{ usertwo.doctor }}
</div>
</div>
</template>
<script>
import { datalisttwo } from "./datalisttwo";
export default {
name: "User",
data() {
return {
usertwos: datalisttwo,
};
},
};
</script>
main.js
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld.vue";
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{ path: "/", name: "User", component: HelloWorld },
{ path: "/:id", name: "UserWithID", component: HelloWorld }
]
});
Vue.config.productionTip = false;
new Vue({
router,
render: (h) => h(App)
}).$mount("#app");
Logic trying to achieve, If i click on router-link id-1 from helloworld.vue component, then in User.vue and Usertwo.vue component. I need to show only array values list which is linked with id-1 only. from two arrray value list based on id.
Similarly on whatever the id, i click on from router-view from helloworld.vue. Same id value, i need to show inside the User and Usertwo.vue component.
Now only issue wit code is, Usertwo array value not loading correctly
I tried below code for that logic, But i couldn't make it.
This is my complete code:- https://codesandbox.io/s/pensive-williamson-n9bi6?file=/src/main.js:0-434
Something like this: https://codesandbox.io/s/white-bird-z6orf
Add props to the components
Send the id from the params to the components
Filter the list
When I refresh my browser few times when I am on "ActorDetails.vue" page/component, not often but sometimes, I lost my actorsData prop data(should have array of 5 objects but become empty array), at first, I thought it's an API's problem but when I try to console.log() the data inside of "App.js", the data exist... I can't seem to find where the problem is.(Also I did try refresh the browser few times when I am on "ActorsList.vue" page/component, the prop data always exist)
Both pages/components("ActorList.vue" and "ActorDetails.vue") gets topActors data from "App.vue".
(Comments in code)
App.vue
<template>
<div id="app">
<router-view name="homePage" />
<router-view :actorsData="topActors" /> <== "ActorList.vue" and "ActorDetails.vue" use this "router-view"
<div class="over-limit-resolution">Over 4k</div>
</div>
</template>
<script>
import { getActors } from "./util/TheMoveDatabase";
export default {
name: "App",
data() {
return {
topActors: [],
};
},
created() {
getActors.then((result) => {
console.log(result); <== Data always came back from API even when my "actorsData" prop inside of "ActorsDetails.vue" lost it's data.
this.topActors = result;
});
},
methods: {},
};
</script>
ActorsList.vue
<template>
<div class="actors-list">
<router-link to="/">Home</router-link>
<div class="actors-list-container" v-if="allFiveActors">
<div
class="actor-container"
v-for="actorData in actorsData"
:key="actorData.id"
>
<router-link :to="'/actorslist/' + actorData.id">
<h3>{{ actorData.name }} | {{ actorData.id }}</h3>
</router-link>
</div>
</div>
</div>
</template>
<script>
export default {
name: "ActorsList",
props: ["actorsData"],
data() {
return {};
},
computed: {
allFiveActors() {
return this.actorsData.length > 0;
},
},
created() {
console.log(this.actorsData); <== Also tried to refresh the browser when I am on this page/component, prop data always exist.
},
};
ActorsDetails.vue (Page/Component that lost prop data)
<template>
<div class="actor-details">
<router-link to="/actorslist">Actors List</router-link>
<h1>Details page</h1>
<div class="actor-details-container" v-if="actorDetails">
<div class="actor-detail-info">
<h3>{{ actorDetails.name }}</h3>
<p>Birthday: {{ actorDetails.birthday }}</p>
</div>
</div>
</div>
</template>
<script>
import { getActorDetails } from "../util/TheMoveDatabase";
export default {
name: "ActorDetails",
props: ["actorsData", "actorId"],
data() {
return {
actorDetails: {},
};
},
methods: {
checkCurrentActorExist() {
const currentActor = this.getCurrentActor;
// console.log(currentActor);
if (!currentActor) {
// this.$router.push("/");
console.log("does not exist");
}
},
getActor() {
const currentActor = this.getCurrentActor;
console.log(currentActor);
console.log("RAN");
if (currentActor) {
getActorDetails(this.actorId).then((result) => {
this.actorDetails = result;
console.log(this.actorDetails);
});
}
},
},
created() {
this.checkCurrentActorExist();
this.getActor();
console.log(this.actorsData); <== When I am on this page/component and refresh the browser few times, sometimes my "actorsData" prop data is lost.
console.log(this.actorId);
},
computed: {
getCurrentActor() {
return this.actorsData.find(
(actor) => actor.id === parseInt(this.actorId)
);
},
},
};
</script>
Routes.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Home',
components: {
homePage: Home,
},
},
{
path: '/actorslist',
name: 'ActorsList',
component: () => import('../views/ActorsList.vue'),
},
{
path: '/actorslist/:actorId',
name: 'ActorDetails',
component: () => import('../views/ActorDetails.vue'),
props(route) {
// console.log(route);
return {
actorId: route.params.actorId,
};
},
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
export default router;
Just a guess, but maybe your loading-method sometimes takes to much time and the empty array already has been passed to the component.
I would try to clear the array and re-fill it with the loaded data instead of creating a new array (I would try to empty it using splice or pop and then refill it with push)
I want to list the array named names of the first object in players using mapState with Vuex. In the current code, the objects in the players are listed according to their titles, but I want to filter them only according to the names in the first object on that page. On second page I want to list them according to the names that I will add to the second object. I hope I was able to explain my problem. How can I do this in the filter? Or what if there is a better way to do this?
Players.vue
<template>
<div class="Players">
<CostumText class="Players-title" tag="h1">Kulüpler</CostumText>
<div class="Players-search">
<input type="text" v-model="search" placeholder="Kulüp ara.." />
<label>Futbolcu ara:</label>
</div>
<div class="Players-inner">
<router-link
:to="players.pathName"
class="Players-inner-wrapper"
v-for="players in filteredList"
v-bind:key="players.id"
>
<div class="Players-inner-cards">
<Clubs class="Players-inner-cards-svg" v-bind:name="players.id" />
<CostumText tag="strong" lang="tr" class="Players-inner-cards-text">
{{ players.title }}
</CostumText>
</div>
</router-link>
</div>
<router-view />
</div>
</template>
<script>
import { mapState } from 'vuex'
import CostumText from '#/components/CostumText'
import Clubs from '#/components/Clubs.vue'
export default {
name: 'Players',
components: {
CostumText,
Clubs
},
data() {
return {
search: ''
}
},
computed: {
...mapState(['players']),
filteredList() {
return this.players.filter((player) =>
player.title.toLowerCase().includes(this.search.toLowerCase())
)
}
},
modules: {}
}
</script>
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
players: [
{
id: 1,
names: ['kerem', 'sirin', 'ali', 'ayse', 'ahmet'],
title: 'Ali',
pathName: 'ali'
},
{
id: 2,
title: 'Ayse',
pathName: 'ayse'
},
{
id: 3,
title: 'Ahmet',
pathName: 'ahmet'
}
]
},
getters: {},
mutations: {},
actions: {},
modules: {}
})
You can modify the filteredList to be
computed: {
...mapState(['players']),
filteredList() {
const filteredPlayers = this.players.filter(player => {
let flag = false;
if(player.names) {
player.names.forEach(name => {
if(name.toLowerCase().includes(this.search.toLowerCase()) flag = true;
});
}
return flag;
});
return filteredPlayers;
},
Here is how you display names
<div class="Players-inner-cards">
<Clubs class="Players-inner-cards-svg" v-bind:name="players.id" />
<CostumText tag="strong" lang="tr" class="Players-inner-cards-text">
{{ players.names.valueOf() }}
</CostumText>
</div>
I am creating a Vue JS app which will display a list of products that when clicked on will link through to a dynamic product by its ID (passed via Vue Router params). This bit works fine but what I need to do is once on that dynamic route, display all the data for that product by its ID. I'm still pretty new to Vue and confused by what approach to take. I don't think I need axios as this won't be an online app so no access to APIs. I also don't know if I need to go as far as using vuex. At present I'm trying to use a simple method to grab the data from my JSON file by the ID passed through the routes parameters. Here's what I have so far...
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Products from './views/Products.vue'
import Product from './views/ProductSingle.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/products',
name: 'products',
component: Products
},
{
path: '/product/:id',
name: 'product',
component: Product,
props: true
}
]
})
Slider.vue - this component is called in Views/Products.vue and is what links through to each single product
<template>
<carousel
:items="3"
:loop="true"
:center="true"
:margin="0"
:dots="false"
:nav="true"
>
<div v-for="product in products" :key="product.productId">
<transition name="slide">
<router-link
:to="{
name: 'product',
params: { id: product.productId }
}"
>
<img src="http://lorempixel.com/100/100/city" :alt="product.name" />
<!-- <img
:src="require('../assets/images/sample-product/' + data.image)"
/>-->
</router-link>
</transition>
</div>
</carousel>
</template>
<script>
import json from '#/json/data.json'
import carousel from 'vue-owl-carousel'
export default {
data() {
return {
products: json
}
},
components: {
carousel
}
}
</script>
ProductSingle.vue
<template>
<div>
<p v-for="product in getData($route.params.id)" :key="product.productId">
{{ product }}
</p>
</div>
</template>
<script>
import json from '#/json/data.json'
export default {
data() {
return {
products: json
}
},
methods: {
getData(id) {
let data = this.products
data.filter(item => {
return item.productId == id
})
}
}
}
</script>
What I as expecting here is that my getData method would return the data for the product at the ID denoted through $route.params.id yet nothing is returned. A console.log(getData($route.params.id)) shows the following:
[{…}]
Which when expanded out shows 0: {__ob__: Observer} and if you expand that observer out there is indeed that data for
image: (...)
name: (...)
productId: (...)
My data.json file looks like the below:
[
{
"productId": 1,
"name": "Test 1",
"image": "sample.jpg"
},
{
"productId": 2,
"name": "Test 2",
"image": "sample.jpg"
},
{
"productId": 3,
"name": "Test 3",
"image": "sample.jpg"
},
{
"productId": 4,
"name": "Test 4",
"image": "sample.jpg"
}
]
Could really do with some guidance on how to approach this problem.
Many thanks in advance
You're missing a return here:
data.filter(item => {
return item.productId == id
})
Try this:
return data.filter(item => {
return item.productId == id
})
If you're not using Api or Vuex then you need to have all the data on a place where they can be fetched from multiple components.
data.json is fine for this.
On your child component, do the following. There is no need for data iteration.
<template>
<div>
{{ singleProduct }}
{{ singleProduct.productId }}
</div>
</template>
<script>
import json from '#/json/data.json'
export default {
name: 'ProductSingle',
data() {
return {
products: json,
singleProduct: undefined
}
},
computed: {
productId () {
return this.$route.params.id // From route
}
},
created () {
this.assignSingleProduct();
},
methods: {
assignSingleProduct() {
let data = this.products
data.filter(item => {
return item.productId == this.productId
})
// Assign to the data
this.singleProduct = data
}
}
}
</script>
I'm trying to use vue-async-data to fetch data asynchronously before rendering my Vue component, but I'm having no success. I'm not getting any erros, but it simply doesn't work.
Here's my main.js code:
import Vue from 'vue'
import VueAsyncData from 'vue-async-data'
import router from './router'
import App from './App.vue'
Vue.use(VueAsyncData)
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
And here's my App.vue code:
<template>
<div>
{{ msg }}
<navigation wait-for="async-data"></navigation>
</div>
</template>
<script>
import Navigation from './components/Navigation.vue'
export default {
name: 'app',
components: {
Navigation
},
data: function() {
return {
msg: 'not loaded yet...'
}
},
asyncData: function (resolve, reject) {
// load data and call resolve(data)
// or call reject(reason) if something goes wrong
setTimeout(function () {
// this will call `vm.$set('msg', 'hi')` for you
resolve({
msg: 'hi'
})
}, 1000)
}
}
</script>
The msg value doesn't change at any moment, but the component is still rendered.
Am I missing somenthing?
As Bert Evans stated, vue-async-data doesn't work with Vue 2.0.
I used vue-router and the created function to achieve what I needed (as suggested in: https://router.vuejs.org/en/advanced/data-fetching.html.
<template>
<div>
<div class="loading" v-if="loading">
Loading...
</div>
<div v-if="error" class="error">
{{ error }}
</div>
<navigation v-if="currentUser"></navigation>
</div>
</template>
<script>
import Navigation from './components/Navigation.vue'
export default {
name: 'app',
components: {
Navigation
},
data: function() {
return {
loading: true,
error: false,
currentUser: null
}
},
created: function() {
this.fetchUserData()
},
methods: {
fetchUserData: function() {
this.$http.get('/Account/CurrentUserInfo').then(data => {
this.currentUser = data
this.loading = false
}, response => {
this.loading = false
this.error = true
});
}
}
}
</script>