Chapter 05

Vue View Router

hello_yogurt
hello_yogurt
2022.07.23に更新

frontend/src/router/index.js

frontend/src/router/index.js
import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: () =>
      import("../views/Home.vue")
  },
  {
    path: "/about",
    name: "About",
    component: () =>
      import("../views/About.vue")
  },
  {
    path: "/amazon_rakuten",
    name: "Amazon_rakuten",
    component: () =>
      import("../views/Amazon_rakuten.vue")
  },
  {
    path: "/check",
    name: "Check",
    component: () =>
      import("../views/Check.vue")
  },
  {
    path: "/item_url",
    name: "Item_url",
    component: () =>
      import("../views/Item_url.vue")
  },
  {
    path: "/line",
    name: "Line",
    component: () =>
      import("../views/Line.vue")
  },
  {
    path: "/cloudwatch_event",
    name: "Cloudwatch_event",
    component: () =>
      import("../views/Cloudwatch_event.vue")
  },
  {
    path: "/loading",
    name: "Loading",
    component: () =>
      import("../views/Loading.vue")
  },
  {
    path: "/mypage",
    name: "Mypage",
    component: () =>
      import("../views/Mypage.vue")
  },
  {
    path: "/result",
    name: "Result",
    component: () =>
      import("../views/Result.vue")
  },
  {
    path: "/edit",
    name: "Edit",
    component: () =>
      import("../views/Edit.vue")
  },
  {
    path: "/delete",
    name: "Delete",
    component: () =>
      import("../views/Delete.vue")
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

export default router;


frontend/src/views/Item_url.vue

・ページ遷移の時のデータ渡し

router-link :to="{ name: 'Check',
          params: {
            item_name : item_name,
            item_url  : item_url
            } }"


受け取る側

data () {
    return {
      item_name : this.$route.params.item_name,
      item_url  : this.$route.params.item_url,
    }
  }

frontend/src/views/Check.vue
・axiosのpost

import axios from "axios"
import Cookies from 'js-cookie'

const csrfToken = Cookies.get('csrftoken')
console.log("csrfToken出力", csrfToken)
const requestHeader = {
  headers: {
    'X-CSRFToken': csrfToken
  }
}
console.log("requestHeader出力", requestHeader)


export default {
  name: 'Check',
  data () {
    return {
      item_name : this.$route.params.item_name,
      item_url  : this.$route.params.item_url,
    }
  },
  methods:{
    WebScraping(){
      const username = Cookies.get('username');
      axios
        .post(
          "/post/",
        {
          username  : username,
          item_name : this.$route.params.item_name,
          item_url  : this.$route.params.item_url
        },
          requestHeader
        )
       .then((res) => {
             console.log(res);
             this.posts = res.data.posts;
        })
        .catch((err) => {
          console.log(err);
        });
    },

frontend/src/views/Loading.vue

・ローディングアイコン

<vue-loading type="spin" color="#333" :size="{ width: '50px', height: '50px' }"></vue-loading>

import { VueLoading } from 'vue-loading-template'

export default {
  components: {
    VueLoading
  },

・何秒までローディングを行うか、その後ページ遷移、scraping_atでいつスクレイピングしたか記載

  mounted() {
      this.Timer();
  },
  methods: {
    Timer(){
      const timerId = setInterval(Loading, 1000);
      var counter = 0;
        function Loading(){
            if(++counter > 100){
              clearInterval(timerId);
              router.push({ path: '/result', query: { message: '「スクレイピングに失敗しました」'} })
            }
            console.log('this time number is: ' + counter);
          axios
            .get("/items/")
            .then(response => {
              this.info = response;
              console.log("取得成功", response);
              const scraping_at = this.info.data.results[0].scraping_at
              scraping_at_list.push(scraping_at);
              if (scraping_at_list[0] != scraping_at){
                clearInterval(timerId);
                router.push('/result');
              }
            });
        }
    }
  }

frontend/src/views/Mypage.vue

・テーブル内のテキストが長文の時に、...で省略

<td>
<span
class="d-inline-block text-truncate"
 style="width:15em;"
 >
{{ items.item_name }}
</span>
</td>

・username(ログインしている)ごとにItemを表示している

mounted() {
    const id = Cookies.get('id');
    axios
      .get("/items/"+id+"/")
      .then(response => {
        this.info = response;
        console.log("取得成功", response);
      });
  }


Django

backend/myapp/views.py
class ItemDetailAPIview(generics.ListAPIView):
    serializer_class = ItemSerializer

    def get_queryset(self):
        username = self.kwargs['username']
        return Item.objects.filter(username=username).order_by("-id")

backend/myapp/urls.py
urlpatterns = [
path('items/<int:username>/', ItemDetailAPIview.as_view(), name="item-detail"),

frontend/src/views/Edit.vue
編集の入力欄

<v-textarea
        label="item_name"
        v-model="edit_item.item_name"
        hint="For example, flowers or used cars"
      ></v-textarea>


axiosのput

  methods:{
    Edit(){
      axios
        .put(
          "/put/",
        {
          id        : this.edit_item.id ,
          item_name : this.edit_item.item_name ,
          item_url  : this.edit_item.item_url ,
          stock     : this.edit_item.stock ,
        },
          requestHeader
        )
         .then((res) => {
               console.log(res);
               this.puts = res.data.puts;
               router.push('/');
          })
          .catch((err) => {
            console.log(err);
          });
      },
    },

Django側

views.py
class Crud(View):
    def put(self, request):

        put = json.loads(request.body.decode("utf-8", "ignore"))
        put_id = put['id']

        put_object = Item.objects.filter(id=put_id)[0]
        print("put_object出力", put_object)


        put_object.item_name = put['item_name']
        put_object.item_url  = put['item_url']
        put_object.stock     = put['stock']

        print("item_name出力", put_object.item_name)

        put_object.save()

        print("put_object出力", put_object)

        return JsonResponse(put)

urls.py
path('put/', Crud.as_view(), name='put'),

frontend/src/views/Delete.vue


frontend/src/views/Line.vue


frontend/src/views/Cloudwatch_event.vue