最近都在做 vue 相关的项目, 在公司推行前后端分离, 重构以前的项目, 真的好忙, 一个项目接着一个, 爬不完的坑, 不说了, 说多了都是眼泪. 开始正文了!!!
Vue 路由切换时页面内容没有重新加载
问题原因: 在组件 mounted 钩子中调用的刷新页面内容, 但测试发现这个钩子没有被调用. 后来发现 App.vue 中使用了: keep-alive 是 Vue 的内置组件, 能在组件切换过程中将状态保留在内存中, 防止重复渲染 DOM. 这就是问题所在了.
解决办法:
使用 Vue 组件切换过程钩子 activated(keep-alive 组件激活时调用), 而不是挂载钩子 mounted:
- <script>
- export default {
- activated: function() {
- this.getData()
- }
- }
- </script>
复制代码
参考网址关于 keep-alive 组件的钩子: https://cn.vuejs.org/v2/api/#activated https://cn.vuejs.org/v2/api/#activated
文件导出方式
项目中涉及到文件导出, 分 xml 和 excel 导出. 不同的文件导出格式不同, 需要根据文件类型判断导出格式.
- exportAllData(val){
- // 全部导出
- if(!val){
- this.exportFile(this.exportAllType);
- }
- },
- exportFile(exportType){
- let url='';// 接口地址
- this.$axios.get(url,{responseType: 'arraybuffer'}).then(res => {
- this.download(res.data,exportType);
- },res => {
- this.$Message.error('导出失败');
- });
- },
- download (data,exportType) {
- if (!data) {
- return
- }
- let exportGs='';
- if(exportType==='excel'){
- exportGs='application/vnd.ms-excel';
- }else if(exportType==='xml'){
- exportGs='text/xml';
- }
- let url = window.URL.createObjectURL(new Blob([data],{type: exportGs}));
- let link = document.createElement('a')
- link.style.display = 'none'
- link.href = url;
- link.setAttribute('download', '文件');
- document.body.appendChild(link)
- link.click();
- }
复制代码
在 vue 多层次组件监听动作和属性的时候可以使用如下方式进行监听
v-bind="$attrs" v-on="$listeners"
复制代码
Vue 2.4 版本提供了这种方法, 将父组件中不被认为 props 特性绑定的属性传入子组件中, 通常配合 interitAttrs 选项一起使用. 之所以要提到这两个属性, 是因为两者的出现使得组件之间跨组件的通信在不依赖 vuex 和事件总线的情况下变得简洁, 业务清晰.
比如组件 A=>B 组件 =>C 组件等, 这种多层级组件, A 组件向 C 组件传递数据或者 C 组件的事件要触发 A 组件中的事件的话, 就可以在 B 组件中写成
- <template>
- <div>
- <span>{{child1}}<span>
- <!-- C 组件中能直接触发 test 的原因在于 B 组件调用 C 组件时 使用 v-on 绑定了 $listeners 属性 -->
- <!-- 通过 v-bind 绑定 $attrs 属性, C 组件可以直接获取到 A 组件中传递下来的 props(除了 B 组件中 props 声明的) -->
- <c v-bind="$attrs" v-on="$listeners"></c>
- </div>
- </template>
- <script>
- import c from './c.vue';
- export default {
- props: ['child1'],
- data () {
- return {};
- },
- inheritAttrs: false,
- components: { c },
- mounted () {
- this.$emit('test1');
- }
- };
- </script>
复制代码
C 组件
- <template>
- <div>
- <span>{{child2}}<span>
- </div>
- </template>
- <script>
- export default {
- props: [child2'],
- data () {
- return {};
- },
- inheritAttrs: false,
- mounted () {
- this.$emit('test2');
- }
- };
- </script>
复制代码
A 组件:
- <template>
- <div id="app">
- <b :child1="child1" :child2="child2" @test1="test1" @test2="test2"></b>
- </div>
- </template>
- <script>
- import b from './b.vue';
- export default {
- data () {
- return {
- child1:'hello child1',
- child2:'hello child2'
- };
- },
- components: { b },
- methods: {
- test1 () {
- console.log('test1');
- },
- test2 () {
- console.log('test2');
- }
- }
- };
- </script>
复制代码
记录日常开发中用到的一些知识点, 权当一次总结吧.
来源: https://juejin.im/post/5b349e0e518825749d2d66ee