仅作记录之用
<body>
<!-- TODO:补全代码实现目标效果 -->
<div id="app">
<list v-if="!fstore.selectedFlower"></list>
<detail v-if="fstore.selectedFlower"></detail>
</div>
<!-- TODOEnd -->
</body>
<script type="module">
const { createApp, onMounted } = Vue;
const { createPinia } = Pinia;
const app = Vue.createApp({
setup() {
// TODO:补全代码实现目标效果
const fstore = useFlowerStore()
onMounted(async() => {
await axios.get("./js/flowers.json").then((res) => {
// console.log(res.data)
fstore.flowers = res.data
console.log(fstore.flowers)
});
//用于判断刷新页面后停留界面
if(localStorage.getItem("choose")!=null){
fstore.selectedFlower = JSON.parse(localStorage.getItem("choose"))
}
});
return {
fstore,
}
// TODOEnd
},
});
app.component("list", FlowerList);
app.component("detail", FlowerDetails);
app.use(createPinia());
app.mount("#app");
</script>
flowerDetails.js
// TODO:补全代码实现目标效果
const FlowerDetails = {
template: `
<div class="flower">
<h2 class="flower-name">{{store.selectedFlower.name}}</h2>
<img :src="store.selectedFlower.image">
<p class="flower-description">{{store.selectedFlower.language}}</p>
<button type="info" @click="returnfl()">返回</button>
</div>
`,
setup() {
const store = useFlowerStore()
function returnfl(){
localStorage.removeItem("choose")
store.selectedFlower = null
}
return {
store,
returnfl,
}
},
};
// TODOEnd
flowerList.js
// TODO:补全代码实现目标效果
const FlowerList = {
template: `
<div class="flower-list">
<div class="flower-card" v-for="(fl,index) in store.flowers" :key="index">
<h2 class="name">{{fl.name}}</h2>
<p class="scientific-name">{{fl.scientificName}}</p>
<div class="description">{{fl.description}}</div>
<button type="primary" @click="toDetail(fl)">查看详情</button>
</div>
</div>
`,
setup() {
const store = useFlowerStore()
function toDetail(fl){
store.selectedFlower = fl
localStorage.setItem("choose", JSON.stringify(fl))
};
return {
store,
toDetail,
}
},
};
// TODOEnd
store.js的内容如下(题目提供)
const { defineStore } = Pinia;
const { ref } = Vue;
const useFlowerStore = defineStore("useFlowerStore", {
state: () => ({
flowers: [], // 所有花卉信息
selectedFlower: null, // 当前选中的花
}),
// TODO:补全代码实现目标效果
getters: {},
actions: {},
// TODOEnd
});
心得:
- 使用Pinia存放全局变量
- 若想刷新页面后保持当前页面的状态,可结合localStorage去实现