根据选项 astro.Build 过滤数据

问题描述 投票:0回答:1

如何根据您从自定义选择中选择的选项(例如国家/地区)过滤数据,并且在 astro.Build 中更改页面时保留该选项

我的数据是json格式的,根据用户选择的选项,数据被过滤而不影响网站上页面更改时的选项

javascript html astrojs
1个回答
0
投票

假设

src/data.json
文件如下:

[
  { "country": "us", "title": "United States" },
  { "country": "gb", "title": "Great Britain" }
]

src/pages/country/[country].astro
中你输入:

---
import data from '../../data.json'

const { country } = Astro.params
const countryData = data.find(c => c.country === country)
---

<h1>{countryData.title}</h1>

现在您应该已经能够在浏览器中访问

http://localhost:4321/country/us

现在对于下拉菜单,将类似这样的内容放入

src/pages/index.astro

---
import data from '../data.json'
---
<select name="country" id="select">
  <option disabled selected></option>
  {data.map(c =>
    <option value={c.country}>{c.title}</option>
  )}
</select>

<script>
  const select = document.getElementById('select') as HTMLSelectElement
  select?.addEventListener('change', e => {
    const { value } = select.options[select.selectedIndex]
    document.location.href = '/country/' + value
  })
</script>
© www.soinside.com 2019 - 2024. All rights reserved.