Vite hash routing mode project packaging and online access to json file method

1. Set the hash routing mode in the index.ts file under the route folder of the vite project

Use createWebHashHistory as shown:
insert image description here

2. Configure the "vite.config.ts" file

export default defineConfig({
    
    
  base: './'
  // 其他配置项、、、
})

as the picture shows:
insert image description here

3. The json file is placed under the "public" folder

The files placed locally in the "public" folder will not be processed after the vite project is packaged, and will be directly placed in the "dist" folder. If they are placed in the "assets" folder, the json files will not be packaged together , there is no json file under the packaged "dist" folder

insert image description here

Fourth, read the json file method: axios

You can use axios to read json files

1. Install axios first: npm i axios -S

Use "npm i axios -S" to install axios and add dependency records to "pakage.json" under the "dependencies" option, because both development and online environments use

After installation, as shown in the figure:
insert image description here

2. How to use axios

Import axios into the single file component and then you can use it:

Note: To read files under public, write "./file path", write "./" in front, and write "/", the json file cannot be accessed online after packaging

For example, the json file in the local project is placed in "pulic/data/test.json",
then when reading and modifying the file, write - - -axios.get('./data/test.json')

The sample code is as follows:

<script setup lang="ts">
import axios from 'axios'

axios
  .get('./data/test.json')
  .then((res) => {
      
      
    console.log(res)
  
  })
  .catch((error) => {
      
      
    console.error(error)
  })

</script>

Guess you like

Origin blog.csdn.net/qq_39111074/article/details/131456008