使用前面学过的vue3框架的知识来制作一个简单的相册
知识点:https://blog.csdn.net/DZ_OP/article/details/144009207?spm=1001.2014.3001.5501
首先我们来看一下完整的代码,通过剖析这些代码一步步学会如何运用所学知识
注意:四张图片的路径为:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>相册</title><style>.clear_ele::after{content: ""; /* 这个伪元素的内容属性必须有 */display: block;clear: both;}.box{margin-bottom: 20px;padding: 0;}.button{background-color: bisque;width: 20px;float: left; text-align: center;margin-right: 10px;border-radius: 8px;cursor: pointer; }.img{width: 480px; height: 240px;border: 1px bisque solid;}</style>
</head><body><div id="app"><h2>基于Vue3实现的相册:展示第{{ img.number }}张相片</h2><img v-bind:src="img.url" class="img"> <ul type="none" class="clear_ele box"><li v-for="(val, idx) in 4" @click="jump(val)" class="button"> {{val}} </li></ul><button @click="prev">上一张</button> <button @click="next">下一张</button></div><script type="module">import { createApp, ref, reactive } from './vue.esm-browser.js'createApp({setup() {// 【定义数据】const img = reactive({number: 1,url: "./img_src/logo1.png"})// 【定义函数】//上一张const prev = () => {img.number--if (img.number == 0) {img.number = 4}img.url = `./img_src/logo${img.number}.png` } //下一张const next = () => {img.number++if (img.number == 5) {img.number = 1}img.url = `./img_src/logo${img.number}.png`}//跳转const jump = (val) => {img.number = valimg.url = `./img_src/logo${img.number}.png`}return {img, prev,next,jump}}}).mount("#app")</script>
</body></html>
示例效果:
首先我们需要写好一个基本的html框架,css里必须写进防止高度塌陷的代码,才不会导致块与块之间展现出”丑陋“的样子。
<style>.clear_ele::after{content: ""; /* 这个伪元素的内容属性必须有 */display: block;clear: both;}.box{margin-bottom: 20px;padding: 0;}.button{background-color: bisque;width: 20px;float: left; text-align: center;margin-right: 10px;border-radius: 8px;cursor: pointer; }.img{width: 480px; height: 240px;border: 1px bisque solid;}</style>
接着vue框架部分,我们需要先导入模块
import { createApp, ref, reactive } from './vue.esm-browser.js'
使用响应式数据reactive来定义数据
const img = reactive({number: 1,url: "./img_src/logo1.png"})
通过v-bind来绑定数据,使得”上一张“按钮做出了事件行为(里面写了一个if函数来实现图片路径的自减)
<button @click="prev">上一张</button>
const prev = () => {img.number--if (img.number == 0) {img.number = 4}img.url = `./img_src/logo${img.number}.png` }
同样的做法,为”下一张“按钮做出用样的操作(会做一个按钮就会做第二个第n个按钮)
<button @click="next">下一张</button>const next = () => {img.number++if (img.number == 5) {img.number = 1}img.url = `./img_src/logo${img.number}.png`}
接着我们需要使用反引号来实现控制这个字符,v-for做一个遍历来实现跳转功能
const jump = (val) => {img.number = valimg.url = `./img_src/logo${img.number}.png`}
<ul type="none" class="clear_ele box"><li v-for="(val, idx) in 4" @click="jump(val)" class="button"> {{val}} </li></ul>
最后将其暴露出来
return {img, prev,next,jump}
这样我们一个简单的相册就制作完成了