Просмотр исходного кода

reuse category component instead of creating a new path for every category

tati 9 лет назад
Родитель
Сommit
90eb223c9c
2 измененных файлов с 18 добавлено и 19 удалено
  1. 1 1
      client/index.html
  2. 17 18
      client/js/main.js

+ 1 - 1
client/index.html

@@ -129,7 +129,7 @@
     </template>
 
     <template id="category">
-        <div class="row">
+        <div class="row" :key="$route.params.category">
             <h5 class="category-name">{{ category }}</h5>
             <div>
                 <ul class="product-list">

+ 17 - 18
client/js/main.js

@@ -121,25 +121,20 @@ function getProducts(category) {
     return productsByCategory[category]
 }
 
-function categoryComponent(categoryName) {
-    return Vue.component(categoryName, {
-        template: '#category',
-        data: function () {
-            return {
-                category: categoryName,
-                products: getProducts(categoryName)
-            }
+var categoryComponent = {
+    template: '#category',
+    props: ['category'],
+    data: function () {
+        return {
+            products: getProducts(this.category)
+        }
+    },
+    watch: {
+        $route: function (to, from) {
+            this.products = getProducts(to.params.category)
         }
-    })
-}
-
-var productChildren = Object.keys(productsByCategory).map(function (p) {
-    return {
-        path: p,
-        name: p,
-        component: categoryComponent(p)
     }
-})
+}
 
 var routes = [{
         path: '/',
@@ -154,7 +149,11 @@ var routes = [{
         path: '/productos',
         component: productos,
         text: 'Productos',
-        children: productChildren
+        children: [{
+            path: ':category',
+            component: Vue.component('category', categoryComponent),
+            props: true
+        }]
     }
 ]