vue:使用不同参数跳转同一组件,实现动态加载图片和数据,以及利用localStorage和vuex持久化数据
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了vue:使用不同参数跳转同一组件,实现动态加载图片和数据,以及利用localStorage和vuex持久化数据,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2363字,纯文字阅读大概需要4分钟。
内容图文
需求:通过不同的参数复用同一组件,实现动态加载数据和图片,同时,在页面刷新时,图片依旧可以加载成功。
过程出现的bug和问题:
1、使用params传参后,再次刷新页面,参数丢失导致数据无法再次加载
2、改用query进行传参后,页面刷新后图片无法加载,这是由于图片的url是在created钩子函数调用查询数据api后才进行赋值,而赋值之后页面已经渲染完成,导致图片无法加载成功
解决方案:
1、通过localStorage将数据持久化,在跳转到当前路由时,先使用localStorage将数据持久化,这里可以配合vuex进行操作
2、页面渲染前,图片的url直接读取localStorage的值,就不会出现页面渲染完成,url还没被赋值导致图片无法加载的情况
附上代码:
需要从 /zyview 跳转至 /viewmessage
/zyview跳转部分:
this .$router.push({ // path: `/viewmessage/${this.names[index]}`, // 使用下列方法方法跳转路由,就不会出现点击tab后再次跳转的bug name: "viewmessage", query: { name: this.lists[index].m_name, // 此为药品名称 index: index, // 药材索引 mid: this.lists[index].id, // 药材id// imgpath: this.lists[index].img_path }, });
触发跳转的方法:
gotodescribe(e,index) { console.log( this .lists[index].id) console.log( this .test) const path = this.lists[index].img_path // 这里path和index是和store中actions方法里面的变量名意义对应,名字不对应无法传值this.$store.dispatch(‘addimagepath‘, {path,index}) console.log("存储内容" + this.$store.state.imgpath.imgpaths[this.$route.query.index]) this.$router.push({ // path: `/viewmessage/${this.names[index]}`,// 使用下列方法方法跳转路由,就不会出现点击tab后再次跳转的bug name: "viewmessage", query: { name: this.lists[index].m_name, // 此为药品名称 index: index, // 药材索引 mid: this.lists[index].id, // 药材id// imgpath: this.lists[index].img_path }, }); },
这是跳转前将数据持久化的步骤:
this.$store.dispatch(‘addimagepath‘, {path,index})
以下为vuex部分,新建一个文件写此存储图片路径的模块:
const state = { // 图片路径 imgpaths: [], // imgpaths: localStorage.getItem(imgpaths[index]), test: "b4b797913756456bb5ffd8d661ab79e5.jpg" } const getters = { } // 改变state状态 const mutations = { addimgpath(state,{path,index}){ state.imgpaths[index] = path localStorage.setItem(index,path) // 这里使用localStorage持久化数据,后面页面就直接读取localStorage中的数据 } } const actions = { addimagepath(context,{path,index}){ context.commit(‘addimgpath‘,{path,index}) } } export default { state, getters, mutations, actions }
/viewmessage部分:
< el-image :src ="`http://image.zysuyuan.cn:8031/${this.path}`" style ="width: 400px; height: 400px" :fit ="fit" alt ="药材" ></ el-image >
data() { return { path: localStorage.getItem( this .$route.query.index), ......... } }
created和watch:
created() { this .fetchData(); }, watch: { $route(to, from) { this.path = localStorage.getItem(this.$route.query.index); this.fetchData(); } },
原文:https://www.cnblogs.com/flypig666/p/11779796.html
内容总结
以上是互联网集市为您收集整理的vue:使用不同参数跳转同一组件,实现动态加载图片和数据,以及利用localStorage和vuex持久化数据全部内容,希望文章能够帮你解决vue:使用不同参数跳转同一组件,实现动态加载图片和数据,以及利用localStorage和vuex持久化数据所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。