The source code for this blog is available on GitHub.
Note
Top

automation script

Cover Image for automation script
Chen Han
Chen Han

動態載入圖片路徑

關於動態載入圖片的還真踩了不少雷。

require 無法使用動態路徑

理想上的寫法:

const methods = {
  ...,
  ...,
  id() {
    return this.$route.params.id
  },
  article() {
    return this.$route.params.article.toString().padStart(2, '0')
  },
  imagePath() {
    try {
      return require(`@/assets/images/articles/${this.id}/${this.article}.jpg`);
    } catch(error) {
      return require(`@/assets/images/articles/default.jpg`);
    }
  },
  videoPath() {
      try {
        return require(`@/assets/video/${this.id}/${this.article}.mp4`);
      } catch(error) {
        try {
          console.log('Error:', error);
          return require(`@/assets/video/${this.article}/${this.article}.MP4`);
        } catch(error2) {
          console.log('Error:', error2);
        }
      }
    },
}

不過上面的寫法雖然看起來可行,實際上沒有辦法寫得太動態

原因:

Based on how the packager works, this isn't really possible with require.

Packaging happens once before runtime so those variables don't have values yet.

建議做法:

You could also create a single file that just serves to require all of the needed components into an object and then exports that object. Then all you need to do is require that single file.

可以這樣寫:

const methods = {
  ...,
  ...,
  imagePath() {
    try {
      return require(`@/assets/images/articles/${this.$route.params.id}/${this.$route.params.article.toString().padStart(2, '0')}.jpg`);
    } catch(error) {
      return require(`@/assets/images/articles/default.jpg`);
    }
  },
  videoPath() {
      try {
        return require(`@/assets/video/${this.$route.params.id}/${this.$route.params.article.toString().padStart(2, '0')}.mp4`);
      } catch(error) {
        try {
          console.log('Error:', error);
          return require(`@/assets/video/${this.$route.params.id}/${this.$route.params.article.toString().padStart(2, '0')}.MP4`);
        } catch(error2) {
          console.log('Error:', error2);
        }
      }
    },
}

小聰明

對某表單先填輸入框,再按下查詢按鈕

function handleClick() {
  const orderNameInput = document.getElementById('orderNameInput')
  const orderQueryButton = document.getElementById('query-order-btn')
  console.log('qwertyuiop');
  /* 填入訂單編號 */
  orderNameInput.value = #{order.name}
  /* 按鈕按下去 */
  orderQueryButton.click()
}

document.getElementById('addReturnButton').addEventListener('click', handleClick)

若該頁找得到影片,顯示電影Icon

若有影片檔,則秀出影片Icon提供點選

若沒有影片連結,則使其空白

理想上的做法(參考這篇):

const fs = require('fs')
/* import fs from 'fs' */

const computed = {
	showVideoIcon() {
    const path_base = `@/assets/video/${this.$route.params.id}/${this.$route.params.article.toString().padStart(2, '0')}`
    const path_01 = `${path_base}.mp4`
    const path_02 = `${path_base}.mp4`

	  fs?.existsSync(path_01) || fs?.existsSync(path_02)
	}
},

Vue 是用來跑瀏覽器的東西,瀏覽器沒有fs,只有node才有,所以在編譯的時候就會掛掉。

相關解釋:Vue app runs in the browser so no, you can’t import fs or similar modules which have to run on the server

那如何動態的觀察影片狀態呢?實際上只能這樣:

const computed = {
	showVideoIcon() {
	  try {
	    return !!require(`@/assets/video/${this.$route.params.id}/${this.$route.params.article.toString().padStart(2, '0')}.mp4`);
	  } catch {
	    try {
	      return !!require(`@/assets/video/${this.$route.params.id}/${this.$route.params.article.toString().padStart(2, '0')}.MP4`);
	    } catch {
	      return false
	    }
	  }
	}
},

應用

這是誠品的憲哥教我的寫法

理想上的樣子:

const computed = {
  path() {
    return require(<動態載入圖片路徑>)
  }
}

實際上動態的要改成先 import ,依據條件判斷 return 哪一值:

import img1 from require('@/images/img1.jpg');
import img2 from require('@/images/img2.jpg');

const computed = {
  path() {
    if (<滿足某條件>) return img1
    return img1
  }
}

這段回覆則類似憲哥的解答:

Import

類似的議題還有動態import(參考連結

梧想網站的 Markdown 即為使用動態import的方法載入不同的檔案。

import React, {useState, useEffect} from "react";
import {useLocation} from 'react-router-dom';
import 'assets/markdown/theme.scss'
/* import 'assets/markdown/theme-plugin-02.scss' */
import Base from "./base";

/**
 * 參考資料:
 * 1. https://flaviocopes.com/react-router-data-from-route/
 * 2. https://reactrouter.com/web/api/Hooks
 *
 * @param props
 * @returns {JSX.Element}
 */
export default function (props) {
  const {id} = props.match.params
  const [post, setPost] = useState(null);
  /* 偵測 Url 改變 */
  const location = useLocation();

  useEffect(() => {
    import(`markdowns/${id}.md`)
      .then((module) => {
        console.log('What is module:', module);
        console.log('What is typeof(module):', typeof (module));

        fetch(module.default)
          .then((res) => res.text())
          .then((post) => setPost(post))
          .catch((err) => console.error(err));
      })
      .catch((err) => console.error(err));
  }, [location]);

  return <Base post={post} markdown={id}/>;
}

Idea

  • rename markdown file in kebab pattern
  • find the dup photo in an folder
  • find the dup photo inside all the subfolders in an target folder
© 2024 WOOTHINK. All Rights Reserved.
Site MapTerms and ConditionsPrivacy PolicyCookie Policy