add a route with props

This commit is contained in:
Andreas Zweili 2021-09-06 12:42:37 +02:00
parent 8b8f6387ac
commit 9df1a73bc1
3 changed files with 20 additions and 15 deletions

View File

@ -11,7 +11,7 @@ const router = createRouter({
routes: [ routes: [
{ path: '/', redirect: '/products' }, { path: '/', redirect: '/products' },
{ path: '/products', component: AllProducts }, { path: '/products', component: AllProducts },
{ path: '/products/:pid', component: ProductDetails }, { path: '/products/:pid', component: ProductDetails, props: true },
{ path: '/products/add', component: AddProduct } { path: '/products/add', component: AddProduct }
] ]
}); });

View File

@ -6,7 +6,7 @@
<h3>{{ product.title }}</h3> <h3>{{ product.title }}</h3>
<h4>${{ product.price }}</h4> <h4>${{ product.price }}</h4>
<p>{{ product.description }}</p> <p>{{ product.description }}</p>
<router-link to="/products/id">View Details</router-link> <router-link :to="'/products/' + product.id">View Details</router-link>
</li> </li>
</ul> </ul>
</section> </section>
@ -20,7 +20,7 @@ export default {
const loadedProducts = inject('products'); const loadedProducts = inject('products');
return { products: loadedProducts }; return { products: loadedProducts };
}, }
}; };
</script> </script>
@ -45,7 +45,8 @@ li {
padding: 1rem; padding: 1rem;
} }
h3, h4 { h3,
h4 {
margin: 0.5rem 0; margin: 0.5rem 0;
} }
</style> </style>

View File

@ -1,26 +1,30 @@
<template> <template>
<section> <section>
<h2>{{ title }}</h2> <h2>{{ title }}</h2>
<h3>${{ price}}</h3> <h3>${{ price }}</h3>
<p>{{ description}}</p> <p>{{ description }}</p>
</section> </section>
</template> </template>
<script> <script>
import { ref } from 'vue'; import { inject } from 'vue';
export default { export default {
setup() { props: ['pid'],
const title = ref(''); setup(props) {
const price = ref(null); const products = inject('products');
const description = ref(''); const selectedProdcut = products.value.find(
product => product.id === props.pid
);
const title = selectedProdcut.title;
const price = selectedProdcut.price;
const description = selectedProdcut.description;
return { title, price, description }; return { title, price, description };
}, }
}; };
</script> </script>
<style scoped> <style scoped>
section { section {
margin: 3rem auto; margin: 3rem auto;
@ -29,4 +33,4 @@ section {
border-radius: 12px; border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
} }
</style> </style>