vue 使用技巧总结 18.11
前言:
在大概学完 vue 整体框架后,有幸接触到花裤衩大神写的 vue-elementUI-admin 模板框架,把这个模板框架当作 demo,跟着 code 一遍,最大的收获是在以逻辑简单的模板熟悉了一个项目的 code 流程,其中对页面的分割、组件间的通信、路由的设置、vuex和请求的结合以及 axios 的封装等都是收获颇丰。
在目前这个项目中,我又接触到了一些其他技巧,现此纪录。
一、父子组件的生命周期
1.加载渲染过程中:
1 2 3 | 父 beforeCreate -> 父 created -> 父 beforeMount -> 子 beforeCreate -> 子 created -> 子 beforeMount -> 子 mounted -> 父 mounted |
2.子组件更新:
1 2 3 | 父 beforeUpdate -> 子 beforeUpdate -> 子 updated -> 父 updated |
3.父组件更新:
1 | 父 beforeUpdate -> 父 updated |
4.销毁:
1 2 3 | 父 beforeDestroy -> 子 beforeDestroy -> 子 destroyed -> 父 destroyed |
以上过程均为同步。如果想在父组件 beforeCreate
/created/
beforeMount 时发送获取如用户 id 等之类了关键信息以供子组件作为请求参数,注意如果这里是异步请求,那么该请求会落后于子组件的渲染。
二、父组件内子组件的切换
在 vue-ele-admin 模板框架中,所有的页面级组件均是在路由中配置,由路由控制页面的切换,在目前项目中我遇见了如下的切换方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <template> <button @click= "changeMod" ></button> <component :is= "yourMod" ></component> </template> <script> import Amod from 'xxx' import Bmod from 'xxx' export default { data() { return { yourMod: 'Amod' } }, methods: { changeMod() { if ( this .yourMod === 'Amod' ) { this .yourMod = 'Bmod' ; return } this .yourMod = 'Amod' ; } } } </script> |
这个方法可以在组件内自行控制组件的切换,降低了对路由的依赖,这也算是切换组件的一种方法吧。
三、路由参数
1.在 vue-ele-admin 框架中,路由的形式都是 /path1/path2/path3 ... 的形式,而在目前的项目中,使用的路由形式是 /path1?key=value 的形式,于是,在某一个子页面中,我们可以通过 this.$route.query.key 来获取 value;
2.在一个页面1( /path1?key=value )中一个按钮,点击后跳转至里一个页面2( /path2/... )中,同时想把页面1中的某些数据同时传递给页面2,
在页面1中按钮点击事件中使用如下:
1 | this .$router.push({name: 'xxx' ,params: { key1: value1, key2: value2 }}) |
需要注意的是,如果使用 params ,则一定要使用 name,而使用 path 的话, params 会被忽略。query 无影响。
在页面2中需要的地方可以直接从路由中获取:
1 2 3 | if ( this .$route.params.key1 === xxx){ this .xxx = this .$route.params.key2 } |
注意,在页面1中用的是 this.$router,页面2中的用的是 this.$route。
四、vue 中的 $refs
1.在 vue 中我们可以通过 $ref 来获取 dom 节点,但是不推荐这样。
1 2 3 4 5 6 7 8 9 10 11 | <template> <input type= "text" ref= "A" > </template> <script> export default { created() { this .$refs.A.value = "admin" } } </script> |
2.当 ref 用在子组件上时,this.$refs.refName 就会指向子组件实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <template> <div id= "parent" > <child ref= "ref-Child" ></child> </div> </template> <script> import child from 'xxxxxx' export default { components: { child }, mounted() { let childComponent = this .$refs.ref-Child; } } </script> |
3.当 ref 和 v-for 一起使用时,this.$refs.refName 获取到的时一个数组,包含和循环数据源对应的 子组件 / dom 节点。
总结:基本上,在 vue 中我们就可以用 ref / refs 代替 JQuery 中的 $('xx')。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现