前言:
在大概学完 vue 整体框架后,有幸接触到花裤衩大神写的 vue-elementUI-admin 模板框架,把这个模板框架当作 demo,跟着 code 一遍,最大的收获是在以逻辑简单的模板熟悉了一个项目的 code 流程,其中对页面的分割、组件间的通信、路由的设置、vuex和请求的结合以及 axios 的封装等都是收获颇丰。
在目前这个项目中,我又接触到了一些其他技巧,现此纪录。
一、父子组件的生命周期
1.加载渲染过程中:
父 beforeCreate -> 父 created -> 父 beforeMount -> 子 beforeCreate -> 子 created -> 子 beforeMount -> 子 mounted -> 父 mounted
2.子组件更新:
父 beforeUpdate -> 子 beforeUpdate -> 子 updated -> 父 updated
3.父组件更新:
父 beforeUpdate -> 父 updated
4.销毁:
父 beforeDestroy -> 子 beforeDestroy -> 子 destroyed -> 父 destroyed
以上过程均为同步。如果想在父组件 beforeCreate
/created/
beforeMount 时发送获取如用户 id 等之类了关键信息以供子组件作为请求参数,注意如果这里是异步请求,那么该请求会落后于子组件的渲染。
二、父组件内子组件的切换
在 vue-ele-admin 模板框架中,所有的页面级组件均是在路由中配置,由路由控制页面的切换,在目前项目中我遇见了如下的切换方法:
<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中按钮点击事件中使用如下:
this.$router.push({name: 'xxx' ,params: { key1: value1, key2: value2 }})
需要注意的是,如果使用 params ,则一定要使用 name,而使用 path 的话, params 会被忽略。query 无影响。
在页面2中需要的地方可以直接从路由中获取:
if(this.$route.params.key1 === xxx){ this.xxx = this.$route.params.key2 }
注意,在页面1中用的是 this.$router,页面2中的用的是 this.$route。
四、vue 中的 $refs
1.在 vue 中我们可以通过 $ref 来获取 dom 节点,但是不推荐这样。
<template> <input type="text" ref="A"> </template> <script> export default { created() { this.$refs.A.value = "admin" } } </script>
2.当 ref 用在子组件上时,this.$refs.refName 就会指向子组件实例。
<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')。