vue使用记录

vue第一次页面加载会触发哪几个钩子函数?

一共8个阶段

1、beforeCreate(创建前)

2、created(创建后)

3、beforeMount(载入前)

4、mounted(载入后)

5、beforeUpdate(更新前)

6、updated(更新后)

7、beforeDestroy(销毁前)

8、destroyed(销毁后)

DOM 渲染在哪个周期中就已经完成?

mounted() {
    console.log('载入后', 'data和methods之后执行')
},

vue生命周期

// 在实例初始化之后,数据观测(data observer)和event/watcher事件配置之前被调用
beforeCreate()
 
// 实例创建完成之后立即调用,挂载阶段还没开始
created()
 
// 挂载到实例上去之后调用
mounted()
 
// Vue实例销毁后调用
destroyed()

路由History模式打包页面空白

项目放在站点根目录 -- 配置

router/index.js

const router = new VueRouter({
  mode: 'history',
  // base: process.env.BASE_URL,
  base: '/',
  routes,
})

vue.config.js        这里的点可以去掉或添加分别测试下,有时情况不一样,改完要重启项目

module.exports = {
  // 基本路径
  // publicPath: process.env.NODE_ENV == 'development' ? '/' : './'
  publicPath: '/'
}

在 nginx 配置:nginx.conf

    server {
        listen       80;
        server_name  localhost;
		
		location / {
			alias F:/erp/dist/;
            try_files $uri $uri/ /index.html;
        }

    }

改完重启 nginx

项目放在站点二级目录 -- 配置

router/index.js

const router = new VueRouter({
  mode: 'history',
  // base: process.env.BASE_URL,
  base: '/erp_project',
  routes,
})

vue.config.js        这里的点可以去掉或添加分别测试下,有时情况不一样,改完要重启项目

module.exports = {
  // 基本路径
  // publicPath: process.env.NODE_ENV == 'development' ? '/' : './'
  publicPath: './'
}

nginx配置:nginx.conf

/erp_project 与上面 base 一致

    server {
        listen       80;
        server_name  localhost;
		
		location /erp_project {
			alias F:/erp/dist;
			index index.html index.htm;
			if (!-e $request_filename) {
				rewrite ^/(.*) /erp_project/index.html last;
				break;
			}
		}

    }

改完重启 nginx

参考:https://www.jb51.net/article/142831.htm

vue代理

vue.config.js 配置:

使用 devServer 配置项来配置代理服务器,proxy 属性用于配置代理的规则;

/api 表示需要代理的接口路径;

target 属性表示代理的目标服务器地址;

changeOrigin 属性表示是否改变请求的源地址;

pathRewrite 属性用于重写请求的路径(可不写);

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://api.example.com',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

代理后实际请求路径:http://api.example.com/api/

注:配置完要重启项目

有效案例

module.exports = {
  devServer: {
    proxy: {
      '/testapi': {
        target: 'http://192.168.1.1:8300/',
        changeOrigin: true
      }
    }
  },
  publicPath: process.env.NODE_ENV == 'development' ? '/' : './',
  chainWebpack: (config) => {
    if (process.env.analyzer) {
      config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
    }
  }
}

封装的 axios 页面配置

import axios from 'axios'

const ax = axios.create({
  baseURL: '/testapi/',
  headers: { ['Content-Type']: 'application/json' }
})
ax.interceptors.request.use(
  (req) => {
    return req
  },
  (err) => {
    return Promise.reject(err)
  }
)
ax.interceptors.response.use(
  (res) => {
    return res
  },
  (err) => {
    return Promise.reject(err)
  }
)
export default ax

watch监听

// 1. 普通数据类型:
<input type="text" v-model="userName"/>

// 当userName值发生变化时触发
watch: {
  userName (newName, oldName) {
    console.log(newName)
  }
},
// 当值第一次绑定的时候不会执行监听函数,只有当值改变的时候才会执行
// 如果想在第一次绑定的时候执行,则设置 immediate 为 true
watch: {
  userName: {
    handler (newName, oldName) {
      console.log(newName)
    },
    immediate: true
  }
},
// 或
watch: {
  to_data() {
    this.userName= this.to_data
  }
},

// 2.  对象类型:
<input type="text" v-model="cityName.name" />

data (){
  return {
    cityName: { name: '北京' }
  }
},
watch: {
  cityName: {
    handler(newName, oldName) {
      console.log(newName)
    },
    immediate: true,
    deep: true
  }
},
// 当需要监听对象的改变时,此时就需要设置deep为true
// 如果对象的属性较多,可以只监听某一个属性	'cityName.name':
// 数组的变化不需要深度监听
// 在watch中不要使用箭头函数,因为箭头函数中的this是指向当前作用域

vue生成二维码(可带logo)

安装 vue-qr 依赖

npm i vue-qr

 页面使用

<template>
  <div>
    <vue-qr :logoSrc="imageUrl" text="http://www.baidu.com" :size="200" :callback="test"></vue-qr>
  </div>
</template>

<script>
import vueQr from 'vue-qr'
export default {
  data() {
    return {
      imageUrl: require('../../assets/logo.png')
    }
  },

  components: {
    vueQr
  },

  methods: {
    test(dataUrl, id) {
      console.log(dataUrl, id)
    },
  }
}
</script>

官方:vue-qr - npm

参考:深入了解Vue使用vue-qr生成二维码的方法_vue.js_脚本之家

vue点击复制

<template>
  <div>
    <el-button icon="el-icon-copy-document" @click="copyText('内容')"></el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {}
  },

  methods: {
    // 复制方法
    copyText(val) {
      let oInput = document.createElement('input')
      oInput.value = val
      document.body.appendChild(oInput)
      oInput.select()
      document.execCommand('Copy')
      this.$message.success('复制成功')
      oInput.remove()
    }
  }
}
</script>

vue设置页面标题

router => index.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import HomeView from '../views/home.vue'

// meta 设置页面标题
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { title: '首页' },
  }
]

router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})

export default router

vue动态style

 :style="{pointerEvents:(item.matter == 'fee_subsidy' ? 'none' : '')}"

vue动态class

:class="{'clv_subsidy':item.matter == 'fee_subsidy'}"

vue样式穿透

<template>
    <view></view>
</template>

<script>
    export default {
        // 样式穿透
		options: {styleIsolation: 'shared'},
		data() {}
    }
</script>

<style lang="less">
</style>

vue金额格式化

正则:/(?<=\.[0-9]{3})\d+/

苹果不兼容

改为:

value = Math.round(value * 1000) / 1000
value = value.toString()

<input type="digit" placeholder="选填" v-model="formData.loan" @change="loanChange" />
<input type="digit" placeholder="请输入金额" v-model="item.money" @change="moneyChange($event,index)" />

<script>
  methods: {
    moneyFormat(e) {
      var value = e.target.value;
      value = value.toString().replace(/(?<=\.[0-9]{3})\d+/, "");
      var array = value.split(".");
      if (value) {
        if (array.length === 1) {
          return (value += ".00");
        } else if (array.length === 2) {
          const array2 = array[1].split("");
          if (array2.length == 1) {
            return (value += "0");
          } else {
            return value;
          }
        }
      }
    },

    loanChange(e) {
      this.formData.loan = this.moneyFormat(e);
    },

    moneyChange(e, i) {
      this.detailedList.forEach((item, index) => {
        if (index == i) {
          this.detailedList[i].money = this.moneyFormat(e);
        }
      });
    },
 }
</script>

vue使用Object.assign重置data数据

Object.assign(target, source) 对象合并

source 源对象:this.$options.data()

target 目标对象:this.data()

源对象 复制到 目标对象

// 重置全部data数据
resetData() {
    Object.assign(this.$data, this.$options.data())
},

// 重置部分数据 form
resetData() {
    Object.assign(this.$data.form, this.$options.data().form)
},

// 重置带表单验证的页面
resetData() {
    Object.assign(this.$data, this.$options.data())
    this.$nextTick(() => {
        this.$refs.formRef.resetFields()
    })
},

// 赋值方法
this.tableData = this.$options.data().tableData

vue安装vue-router报错

错误:Uncaught TypeError: Cannot read property 'install' of undefined

可能vue-router版本太高

vue.js引入使用

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./vue.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- 计算属性 -->
      <div>
        <div>方法:{{getTime()}}</div>
        <div>属性:{{getTime1}}</div>
      </div>

      <!-- 插槽 -->
      <div>
        <todo class="todo">
          <!-- 完整写法 -->
          <!-- <todo-title slot="todo-title" v-bind:title="titles" v-on:click2="click3"></todo-title> -->
          <todo-title
            slot="todo-title"
            :title="titles"
            @click2="click3"
          ></todo-title>
          <todo-items
            slot="todo-items"
            v-for="items in content"
            :item="items"
          ></todo-items>
        </todo>
      </div>
    </div>

    <script>
      Vue.component("todo", {
        template:
          "<div><slot name='todo-title'></slot><ul><slot name='todo-items'></slot></ul></div>",
      });
      Vue.component("todo-title", {
        props: ["title"],
        template:
          "<div>{{title}}<button @click=\"click1('传值,这里斜杠是转义')\">测试</button></div>",
        methods: {
          click1(chuangz) {
            this.$emit("click2", chuangz);
          },
        },
      });
      Vue.component("todo-items", {
        props: ["item"],
        template: '<li>{{item}}<button  @click="testClick">点击</button></li>',
        methods: {
          testClick() {
            return alert("test");
          },
        },
      });

      let app = new Vue({
        el: "#app",
        data: {
          titles: "标题",
          content: ["内容1", "内容2", "内容3"],
        },
        methods: {
          getTime() {
            return Date.now();
          },
          click3(val) {
            console.log(val);
            return alert("hello");
          },
        },
        computed: {
          getTime1: () => {
            return Date.now();
          },
        },
      });
    </script>
  </body>
</html>

vue回车触发事件

<el-input v-model="req_obj.title" @keyup.enter.native="getProducts">

vue切换路由保留原页面数据

使用vue内置组件 keep-alive 来缓存页面,配合路由选项调用;

设置了 keep-alive 缓存的组件在首次进入组件,会一次调用组件的钩子函数:created --> mounted --> activated ;再次进入时,只触发 activated 钩子函数

<!-- fPage.vue  -->
<template>
  <div class="page-main">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
      <router-view v-if="!$route.meta.keepAlive"></router-view>
  </div>
</template>
<!-- child.vue  -->
<template>
    <el-table :data="tableData" ref="tableRef">
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="name" label="张三"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
    </el-table>
</template>

<script>
  // 使用 keep-alive 后第二次加载只会触发的函数 activated
  activated() {
    this.$nextTick(() => {
      this.$refs.tableRef.doLayout() // 手动重新计算表格宽度(解决表格渲染宽度问题)
    })
    console.log('activated')
  },
</script>
// router.js
{
  path: '/produceCount',
  name: 'produceCount',
  component: produceCount,
  meta: { title: '统计', keepAlive: true } // keepAlive用来判断是否要缓存
}

vue过滤器filter

全局定义自定义过滤器

Vue.filter('toLowercase', function(value) {
  return value.toLowerCase();
});

// 使用 {{ message | toLowercase }}

局部定义自定义过滤器

filters: {
  toUppercase(value) {
    return value.toUpperCase();
  }
}

// 使用 {{ message | toUppercase }}

vue使用element-ui表格el-table出现固定栏位移问题

表格使用 fixed="left" 出现位移问题

watch: {
  tableData: {
    handler() {
      this.$nextTick(() => {
        this.$refs.tableDataRef.doLayout()
      })
    },
    deep: true
  }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Winston是一个非常流行的Node.js日志库,可以轻松地在Vue项目中使用它来记录日志。以下是在Vue项目中使用Winston的步骤: 1. 安装Winston:在终端中使用以下命令安装Winston: ``` npm install winston ``` 2. 创建一个日志文件:在你的Vue项目根目录下创建一个logs文件夹,并在其中创建一个名为app.log的日志文件。 3. 创建Winston实例:在你的Vue项目中创建一个名为logger.js的文件,并在其中创建一个Winston实例,配置日志记录器。以下是一个示例配置: ``` const winston = require('winston'); const path = require('path'); const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.printf(info => `${info.timestamp} [${info.level.toUpperCase()}] ${info.message}`) ), transports: [ new winston.transports.File({ filename: path.join(__dirname, '../logs/app.log') }) ] }); module.exports = logger; ``` 此配置将日志记录级别设置为info,并将日志记录到我们之前创建的app.log文件中。它还使用了Winston的格式化选项,以便在日志中包含时间戳。 4. 在Vue组件中使用日志记录器:在Vue组件中导入logger.js文件,并在需要记录日志的地方使用logger实例。例如: ``` import logger from './logger'; export default { name: 'MyComponent', created() { logger.info('Component created'); }, methods: { handleClick() { logger.warn('Button clicked'); } } }; ``` 在此示例中,我们在组件的created钩子记录了一条“Component created”消息,并在按钮的单击事件处理程序中记录了一条“Button clicked”消息。这些消息将被记录到我们之前创建的app.log文件中。 这就是在Vue项目中使用Winston记录日志的基本步骤。你可以根据需要调整Winston配置,以满足你的特定需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值