Anonymous
Страница сведений о продукте не маршрутинг в Vue JS
Сообщение
Anonymous » 09 фев 2025, 17:38
У меня есть страница списка продуктов и страница ProductDetails. Когда я нажимаю на карту продукта, она должна перейти на эту страницу с подробностями продукта с пройденным идентификатором, но этого не произойдет. < /P>
У меня две консоли. Один для функций ViewDetails фактически вызывается. Я вижу, что это называется как показывает журнал. Другой журнал находится в деталях продукта. Это в жизненном цикле, созданном. Но я не вижу журнала появляется в инструментах DEV.
Код: Выделить всё
[url=#]Intellishop[/url]
Our Products
{{ product.item_name }}
Price: ${{ product.new_price }}
Discount: {{ product.discount }}%
Seller: {{ product.seller }}
Previous
{{ page }}
Next
import axios from 'axios';
// import LoginModal from "./LoginModal.vue";
// import LoginModal from "./Navbar.vue";
// import Navbar from './Navbar.vue';
export default {
data() {
return {
products: [],
currentPage: 1,
pageSize: 8,
totalPages: 0,
};
},
created() {
this.fetchProducts();
console.log("i am being called")
},
methods: {
async fetchProducts(page = 1) {
try {
const response = await axios.get(`http://127.0.0.1:8000/api/products?page=${page}`);
this.products = response.data.results || [];
console.log(this.products)
this.totalPages = Math.ceil(response.data.count / this.pageSize);
this.currentPage = page;
} catch (error) {
console.error("There was an error fetching the products!", error);
}
},
navigateToLogin() {
// Replace with your actual login route
this.$router.push('/login');
},
viewDetails(productId) {
console.log("Navigating to:", `/product/${productId}`); // Debugging log
this.$router.push(`/product/${productId}`).catch(err => {
if (err.name !== "NavigationDuplicated") console.error(err);
});
},
}
};
< /code>
my index.js внутри папки маршрутизатора < /p>
import Vue from 'vue';
import VueRouter from 'vue-router';
import ProductDetails from '../components/ProductDetails.vue';
// import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{ path: '/product/:id', component: ProductDetails },
];
// const router = createRouter({
// history: createWebHistory(process.env.BASE_URL),
// routes,
// });
const router = new VueRouter({
mode: 'history', // Correct for Vue Router v3
routes,
});
export default router;
< /code>
my productdetails.vue < /p>
Product Details
[b]Name:[/b] {{ product.item_name }}
[b]Price:[/b] ${{ product.new_price }}
[b]Discount:[/b] {{ product.discount }}%
[b]Seller:[/b] {{ product.seller }}
export default {
data() {
return {
product: null, // Start with no product
};
},
created() {
console.log("ProductDetails component created.");
this.fetchProductDetails();
},
methods: {
async fetchProductDetails() {
const productId = this.$route.params.id; // Get ID from the route
console.log(productId)
try {
const response = await axios.get(`http://127.0.0.1:8000/api/products/${productId}`);
this.product = response.data;
} catch (error) {
console.error("Error fetching product details:", error);
}
},
},
};
В чем проблема?
Подробнее здесь:
https://stackoverflow.com/questions/794 ... -in-vue-js
1739111920
Anonymous
У меня есть страница списка продуктов и страница ProductDetails. Когда я нажимаю на карту продукта, она должна перейти на эту страницу с подробностями продукта с пройденным идентификатором, но этого не произойдет. < /P> У меня две консоли. Один для функций ViewDetails фактически вызывается. Я вижу, что это называется как показывает журнал. Другой журнал находится в деталях продукта. Это в жизненном цикле, созданном. Но я не вижу журнала появляется в инструментах DEV.[code] [url=#]Intellishop[/url] Our Products {{ product.item_name }} Price: ${{ product.new_price }} Discount: {{ product.discount }}% Seller: {{ product.seller }} Previous {{ page }} Next import axios from 'axios'; // import LoginModal from "./LoginModal.vue"; // import LoginModal from "./Navbar.vue"; // import Navbar from './Navbar.vue'; export default { data() { return { products: [], currentPage: 1, pageSize: 8, totalPages: 0, }; }, created() { this.fetchProducts(); console.log("i am being called") }, methods: { async fetchProducts(page = 1) { try { const response = await axios.get(`http://127.0.0.1:8000/api/products?page=${page}`); this.products = response.data.results || []; console.log(this.products) this.totalPages = Math.ceil(response.data.count / this.pageSize); this.currentPage = page; } catch (error) { console.error("There was an error fetching the products!", error); } }, navigateToLogin() { // Replace with your actual login route this.$router.push('/login'); }, viewDetails(productId) { console.log("Navigating to:", `/product/${productId}`); // Debugging log this.$router.push(`/product/${productId}`).catch(err => { if (err.name !== "NavigationDuplicated") console.error(err); }); }, } }; < /code> my index.js внутри папки маршрутизатора < /p> import Vue from 'vue'; import VueRouter from 'vue-router'; import ProductDetails from '../components/ProductDetails.vue'; // import { createRouter, createWebHistory } from 'vue-router'; import Home from '../views/Home.vue'; Vue.use(VueRouter); const routes = [ { path: '/', name: 'Home', component: Home, }, { path: '/product/:id', component: ProductDetails }, ]; // const router = createRouter({ // history: createWebHistory(process.env.BASE_URL), // routes, // }); const router = new VueRouter({ mode: 'history', // Correct for Vue Router v3 routes, }); export default router; < /code> my productdetails.vue < /p> Product Details [b]Name:[/b] {{ product.item_name }} [b]Price:[/b] ${{ product.new_price }} [b]Discount:[/b] {{ product.discount }}% [b]Seller:[/b] {{ product.seller }} export default { data() { return { product: null, // Start with no product }; }, created() { console.log("ProductDetails component created."); this.fetchProductDetails(); }, methods: { async fetchProductDetails() { const productId = this.$route.params.id; // Get ID from the route console.log(productId) try { const response = await axios.get(`http://127.0.0.1:8000/api/products/${productId}`); this.product = response.data; } catch (error) { console.error("Error fetching product details:", error); } }, }, }; [/code] В чем проблема? Подробнее здесь: [url]https://stackoverflow.com/questions/79425081/product-detail-page-not-routing-in-vue-js[/url]