Vue.js

相关内容

Vue或Nuxt中如何渲染数学公式?

在网页上,有很多种方法可以渲染漂亮的数学公式。但是这些方法基本上不能直接应用于Vue.js或者Nuxt.js。在本文中,我们将分别说明如何在Vue.js或者Nuxt.js中使用katex和mathjax渲染数学公式。Katex想要自动渲染所有页面上的数学公式,你需要使用CDN来加载katex:<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" href="/poem-studio-favicon-black.svg"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css" integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww" crossorigin="anonymous"> <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js" integrity="sha384-hIoBPJpTUs74ddyc4bFZSM1TVlQDA60VBbJS0oA934VSz82sBx1X7kSx2ATBDIyd" crossorigin="anonymous"></script> <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js" integrity="sha384-43gviWU0YVjaDtb/GhzOouOXtZMP/7XUzwPTstBeZFe/+rCMvRwr4yROQP43s0Xk" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script> <title>Manitori</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.js"></script> </body> </html>如果你使用的是Nuxt.js,那么你需要修改你的nuxt.config.ts://nuxt.config.ts export default defineNuxtConfig({ app: { head: { link: [ {rel:'stylesheet', href:"https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css", integrity:"sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww", crossorigin:"anonymous"} ], script: [ { defer:true, src:"https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js", integrity:"sha384-hIoBPJpTUs74ddyc4bFZSM1TVlQDA60VBbJS0oA934VSz82sBx1X7kSx2ATBDIyd", crossorigin:"anonymous" }, { defer:true, src:"https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js", integrity:"sha384-43gviWU0YVjaDtb/GhzOouOXtZMP/7XUzwPTstBeZFe/+rCMvRwr4yROQP43s0Xk", crossorigin:"anonymous", onload:"renderMathInElement(document.body);" }, ] } } })如果你需要更改renderMathInElement函数的选项,你可以在另一个<script>标签中调用renderMathInElement :<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" href="/poem-studio-favicon-black.svg"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css" integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww" crossorigin="anonymous"> <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js" integrity="sha384-hIoBPJpTUs74ddyc4bFZSM1TVlQDA60VBbJS0oA934VSz82sBx1X7kSx2ATBDIyd" crossorigin="anonymous"></script> <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js" integrity="sha384-43gviWU0YVjaDtb/GhzOouOXtZMP/7XUzwPTstBeZFe/+rCMvRwr4yROQP43s0Xk" crossorigin="anonymous"></script> <script> document.addEventListener("DOMContentLoaded", function() { renderMathInElement(document.body, { // customised options // • auto-render specific keys, e.g.: delimiters: [ {left: '$$', right: '$$', display: true}, {left: '$', right: '$', display: false}, {left: '\\(', right: '\\)', display: false}, {left: '\\[', right: '\\]', display: true} ], // • rendering keys, e.g.: throwOnError : false }); }); </script> <title>Manitori</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.js"></script> </body> </html>需要注意的是,直接使用document.body可能会导致一些关键性错误,见Vue - TypeError: Cannot read properties of null (reading 'insertBefore')。因此,建议将document.body 改为一个特定的渲染区域document.getElementById(Id) ,不过这样的话,你需要每一页都分别调用一次renderMathInElement :<script lang="ts" setup> onMounted(()=>{ nextTick(()=>{ var node = document.getElementById(Id) document.addEventListener("DOMContentLoaded", function() { renderMathInElement(node, { // customised options // • auto-render specific keys, e.g.: delimiters: [ {left: '$$', right: '$$', display: true}, {left: '$', right: '$', display: false}, {left: '\\(', right: '\\)', display: false}, {left: '\\[', right: '\\]', display: true} ], // • rendering keys, e.g.: throwOnError : false }); }); }) }) </script>在Vue.js中,你估计需要异步渲染数学公式,因此可以根据以下示例写:<script lang="ts" setup> var node = document.getElementById(Id) Promise.resolve() .then(()=>{ nextTick(()=>{ document.addEventListener("DOMContentLoaded", function() { renderMathInElement(node, { // customised options // • auto-render specific keys, e.g.: delimiters: [ {left: '$$', right: '$$', display: true}, {left: '$', right: '$', display: false}, {left: '\\(', right: '\\)', display: false}, {left: '\\[', right: '\\]', display: true} ], // • rendering keys, e.g.: throwOnError : false }); }); }) }) </script>Mathjax用mathjax来自动渲染数学公式,比katex要简单得多。跟katex一样,你最好使用CDN来加载mathjax:<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" href="/poem-studio-favicon-black.svg"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@4.0.0-beta.6/tex-chtml.js"> </script> <script> MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']] } }; </script> <title>Manitori</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.js"></script> </body> </html>如果你使用的是Nuxt.js,那么在你的nuxt.config.ts 中添加如下代码://nuxt.config.ts export default defineNuxtConfig({ app: { head: { script: [ { type: "text/javascript", id: "MathJax-script", async: true, src: "https://cdn.jsdelivr.net/npm/mathjax@4.0.0-beta.6/tex-chtml.js", }, { innerHTML: "MathJax = {tex: {inlineMath: [['$', '$'],['$$', '$$']]}};", }, ] })然而在Vue.js中,使用mathjax,你也需要异步渲染数学公式。不然,所有渲染的数学公式都会重新变回原样。为此,你需要使用MathJax.typesetPromise() :<script lang="ts" setup> Promise.resolve() .then(()=>{ nextTick(() => { MathJax.typesetPromise(); }); }) </script>或者你可以使用setTimeout来替代nextTick:setTimeout(() => { MathJax.typesetPromise(); }, 3000);根据上面的做法,你就可以轻松在Vue.js或Nuxt.js中整合katex和mathjax啦😄!
2024-06-06 16:13:27

Vue3+Django实现保持登录状态

Request.session对象会自动生成一个cookie,该cookie名字默认为sessionoid,储存session的session_key值。当会话session过期后,该cookie将会自动消失。只有该cookie清空后,登录后的用户才能重新登录。 通过后端设置session的过期时间,时间到后,通过浏览器可以看到,cookie自动消失了。因此只需要设置,用户存在localStorage中的token值跟着cookie一起消失,就能够通过设置session的过期时间,来控制用户保持登录状态的时间,如七天免登录。 我们可能会认为其实可以根据cookie来控制登录状态,实际上想要在vue中操作cookie值是不容易。在JavaScript中,我们可以通过document.getElementId()之类的指令来控制cookie。但在vue中,使用document的指令很可能会得到空的返回值。因此,不能通过直接控制cookie的方法来实现控制登录状态。 因此,我们需要在后端多写一个接口,来检验token的有效性,从而控制用户的登录状态。 注意:cookie只会影响用户是否能够再次登录,而vue中判断用户登录,使用cookie不方便,因此只能使用token来实现。然而token跟cookie在前端是独立的,因此如果cookie过期了,而token没清除,就会导致一直保持登录,而token清除了,cookie没过期,就会导致登录状态结束后,用户无法登录。
2024-05-02 18:25:10

Some chunks are larger than 500 KiB after minification

When your vue/nuxt project is large, running npm run build  may output the error : WARN 15:32:15 (!) Some chunks are larger than 500 KiB after minification. Consider: - Using dynamic import() to code-split the application - Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks - Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.This is indeed a vite problem. You could solve this error by setting the chunk size limit higher.vite.config.js ://vite.config.js export default defineConfig({ ..., build: { chunkSizeWarningLimit: 1600 } })nuxt.config.ts ://nuxt.config.ts export default defineNuxtConfig({ vite: { build: { chunkSizeWarningLimit: 1600 }, } })
2024-05-02 17:18:43

Vue - TypeError: Cannot read properties of null (reading 'insertBefore')

In Vue 3/Nuxt 3, one may occur the error TypeError: Cannot read properties of null (reading 'insertBefore') which has little information and is hard to solve. In the following, we summerize some tips that help you solve this error :1. Change v-if to v-show , or change all v-if , v-else to v-show. Sometimes, the error appears because there are v-if or v-if, v-else pairs.2. Change katex auto-render. The error may appear because you use katex auto-render. To solve this, you could either change katex to mathjax, or change document.body in the auto-render function to a specific area document.getElementById(Id) as follows :<script> var node = document.getElementById(Id) document.addEventListener("DOMContentLoaded", function() { renderMathInElement(node, { // customised options // • auto-render specific keys, e.g.: delimiters: [ {left: '$$', right: '$$', display: true}, {left: '$', right: '$', display: false}, {left: '\\(', right: '\\)', display: false}, {left: '\\[', right: '\\]', display: true} ], // • rendering keys, e.g.: throwOnError : false }); }); </script>If katex render all corresponding symbols in document.body, it may also influence some normal part. So you need to restrict it to a specific area.3. Change your dialog component. If you are using SSR, like Nuxt.js, the error may occur due to your dialog component in the UI library. You could either try to wrap the dialog with ClientOnly <ClientOnly> <Dialog> </Dialog> </ClientOnly>or try to use another UI library.
2024-05-05 12:19:38

npm run build error: Heap out of memory in Nuxt3

When running npm run build , an error may occur which looked like :<--- Last few GCs ---> [2656:000001DF58927940] 511573 ms: Mark-sweep 2013.9 (2091.6) -> 2012.7 (2091.4) MB, 1022.4 / 0.0 ms (average mu = 0.211, current mu = 0.009) allocation failure; scavenge might not succeed [2656:000001DF58927940] 513611 ms: Mark-sweep 2028.4 (2091.4) -> 2027.2 (2117.4) MB, 2021.5 / 0.0 ms (average mu = 0.083, current mu = 0.008) allocation failure; scavenge might not succeed <--- JS stacktrace ---> FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory 1: 00007FF60B131B7F node_api_throw_syntax_error+203775 2: 00007FF60B0B1556 v8::internal::wasm::WasmCode::safepoint_table_offset+63558 3: 00007FF60B0B28C2 v8::internal::wasm::WasmCode::safepoint_table_offset+68530 4: 00007FF60BB547F4 v8::Isolate::ReportExternalAllocationLimitReached+116 5: 00007FF60BB3FB52 v8::Isolate::Exit+674 6: 00007FF60B9C1BBC v8::internal::EmbedderStackStateScope::ExplicitScopeForTesting+124 7: 00007FF60B9BEDDB v8::internal::Heap::CollectGarbage+3963 8: 00007FF60B9D5013 v8::internal::HeapAllocator::AllocateRawWithLightRetrySlowPath+2099 9: 00007FF60B9D58BD v8::internal::HeapAllocator::AllocateRawWithRetryOrFailSlowPath+93 10: 00007FF60B9E50F3 v8::internal::Factory::NewFillerObject+851 11: 00007FF60B6D6825 v8::internal::DateCache::Weekday+1349 12: 00007FF60BBF1E81 v8::internal::SetupIsolateDelegate::SetupHeap+558193 13: 00007FF5AD7902ACTo solve this error, you could try to change your package.json as follows ://package.json "scripts": { "build": "node --max-old-space-size=8192 node_modules/nuxt/bin/nuxt.mjs build", "dev": "nuxt dev", "generate": "nuxt generate", "preview": "nuxt preview", "postinstall": "nuxt prepare" }Or you could set your nuxt.config.ts ://nuxt.config.ts export default defineNuxtConfig({ sourcemap: false })
2024-05-02 16:19:43

Vue.js与Nuxt.js的区别

Vue.js与Nuxt.js都是前端的两个框架,Vue.js的项目属于单页应用,而Nuxt.js是基于Vue.js的服务端渲染通用框架。单页应用简称SPA,指的是前端代码将会在浏览器端被浏览器渲染。这对SEO优化不利,搜索引擎爬虫,会爬到空的网页。在Vue项目中,Vue会将JS交给浏览器渲染因此,结果是查看源代码没有别的东西,搜索引擎爬虫也基本只能看到这些,于是便直接下一个了,不会等你渲染。而服务端渲染,简称SSR,正是该问题的解决方案。前端代码会先在Node.js服务端渲染,然后再交给浏览器进行“二次渲染”。Nuxt.js则是Vue.js的SSR通用解决方案。前端代码经过服务端渲染后,能让搜索引擎爬虫看到完整的网站,同时查看源代码也能看到完整的代码。服务端渲染能提高网站渲染速度,降低白屏时间。同时,因为要同时运行Node.js服务端,这增加了服务器的负载。在Nuxt.js中,可以设置部分页面SSR,部分页面则是SPA,这样能降低服务器的资源耗费。对于静态网站,可以使用预渲染替代服务端渲染。预渲染,简称SSG,指提前渲染静态的html,提高页面响应。SSG一般适用于文档、个人博客等场景,即数据不会经常性发生变化的场景。SSG同样有利于SEO优化,同时不需要同时运行多一个服务端,降低了服务器的负荷。Nuxt.js中同样可以设置SSG,你可以根据自己的需求,将不同页面分别设置为SSR页面、SPA页面、SSG页面。
2024-05-14 23:32:56

Nuxt 3 Error TypeError: Cannot read properties of null (reading 'shapeFlag')

I encountered such an error when using Nuxt 3.8 :TypeError: Cannot read properties of null (reading 'shapeFlag')The error is a bit misleading to me, because I have defined a Dialog component which is also named Flag . I used Flag in two different pages, one of which was ok, but the other one threw out such an error. I tried to add ClientOnly to Flag , but the error was still there.I thought that the issue is my UI library. I am using ElementUI Plus, and my Flag component is indeed defined by wrapping ElDialog . Adding ClientOnly to ElDialog or renamed the file name of Flag to Flag.client.vue couldn't solve the error. Finally, I was able to solve this problem by using another UI library, i.e. PrimeVue.
2024-05-07 21:08:25

Vue - Go to anchor smoothly without changing url

In Vue.js, we can define an anchor by RouterLink or HTML tag <a> , while in Nuxt.js, we can additionally use NuxtLink which is similar to RouterLink .<a href="#content">My Link</a> <RouterLink to="#content">My Link</RouterLink> <NuxtLink to="#content">My Link</NuxtLink>However, on loading a page, the above ways would change the url which makes it slow to go to #content . To speed up anchor link and not change the url, there are two ways.The first way is to use pure javascript method scrollIntoView to scroll to the specified div id, which is fast and would not change url.function scrollSmoothTo(Id) { var node = document.getElementById(Id); node.scrollIntoView({ behavior: 'smooth' }); } <a @click="scrollSmoothTo('content')"> Scroll to userdiv </a> <RouterLink @click="scrollSmoothTo('content')"> Scroll to userdiv </RouterLink> <NuxtLink @click="scrollSmoothTo('content')"> Scroll to userdiv </NuxtLink> <div id="content"> example </div>Note that adding behavior: 'smooth' can add animation when scrolling. However, using this way, a could not have attribute href, i.e. <a href="#content" @click="scrollSmoothTo('content')" /> <RouterLink href="#content" @click="scrollSmoothTo('content')" /> <NuxtLink href="#content" @click="scrollSmoothTo('content')" />would not perform the click event. This is not SEO friendly.Therefore, the second way is the improvement of the first that is SEO friendly, which can smoothly go to #content without changing the url. We should use Vue's event modifiers for v-on.<a href="#content" @click.native.prevent="scrollSmoothTo('content')"> Scroll to userdiv </a> <div id="content"> example </div>This way, we could prevent the default href action when clicking and perform the scrollSmoothTo function. However, It seems that using RouterLink or NuxtLink in the same way could not prevent the default action, i.e.<RouterLink href="#content" @click.native.prevent="scrollSmoothTo('content')"> Scroll to userdiv </RouterLink> <NuxtLink href="#content" @click.native.prevent="scrollSmoothTo('content')"> Scroll to userdiv </NuxtLink>not work.
2024-04-30 16:52:12

Vue add whitespaces in a string

In Vue.js, if you simply add multiple whitespaces in a string, it eventually displays a single whitespace.//This will display a single whitespace. 'ab c'If you want to display multiple whitespaces, you could use unicode to represent whitespace.let str1 = 'ab\u00A0\u00A0\u00A0 c'; let str2 = 'ab\u0020\u0020\u0020 c'; let str3 = 'ab\u3000\u3000\u3000 c';These will output multiple whitespaces in strings.
2024-05-09 20:18:57

el-input 限制 只能输入数字,数字大小,长度,小数点后位数以及字母e的限制

通常情况下在使用elementUI前端框架的时候,经常会遇到表单要限制输入内容,尤其是数字。话不多说,代码如下: <el-input v-model="form.plan" type="number" step="0.5" min="0" max="5" @keyup.native="proving($event)" @input="editInput($event,'plan')" placeholder="最高5分" oninput="if(value>5)value=5;if(value<0)value=0" ></el-input>第一个属性:type=“number” input的原生属性,标明input框的类型第二个属性: step=“0.5” input的原生属性,type=“number” 时生效, 标明输入字段的合法数字间隔(假如 step=“0.5”,则合法数字应该是 -0.5、0、0.5、1,以此类推)第三个属性: min=“0” max=“5” min 属性规定输入字段所允许的最小值。 max 属性规定输入字段所允许的最大值。 min 属性与 max 属性配合使用,可创建合法值范围。第四个属性:@keyup.native="proving($event)"proving(e){ var val=e.target.value; //限制只能输入一个小数点 if (val.indexOf(".") != -1) { var str = val.substr(val.indexOf(".") + 1); if (str.indexOf(".") != -1) { val = val.substr(0, val.indexOf(".") + str.indexOf(".") + 1); } } e.target.value = val.replace(/[^\d^\.]+/g,''); },第五个属性:@input="editInput($event,‘plan’)"editInput(value, name) { this.form[name] = ("" + value) // 第一步:转成字符串 .replace(/[^\d^\.]+/g, "") // 第二步:把不是数字,不是小数点的过滤掉 .replace(/^0+(\d)/, "$1") // 第三步:第一位0开头,0后面为数字,则过滤掉,取后面的数字 .replace(/^\./, "0.") // 第四步:如果输入的第一位为小数点,则替换成 0. 实现自动补全 .match(/^\d*(\.?\d{0,1})/g)[0] || ""; // 第五步:最终匹配得到结果 以数字开头,只有一个小数点,而且小数点后面只能有0到2位小数 },第六个属性: placeholder=“最高5分” 提示内容第七个属性:οninput="if(value>5)value=5;if(value<0)value=0"表示:如果输入内容大于5 ,就输出5 ,如果输入内容小于0 输出0elementUI中el-input输入数字且保留指定小数位<!-- 如果需要保留两位小数或者三位小数 只需要将 最后的 +2 改为 +3 即可 以此类推,保留几位小数就 几+1 --> <el-input type="text" placeholder="请输入保留一位小数的数字" v-model="userValue" oninput="if(isNaN(value)) { value = parseFloat(value) } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+2)}" />因项目需要在此记录下此文章是我开发过程的一个记录,方便我日后学习和复盘。若能帮到你不胜荣幸。原文链接:https://blog.csdn.net/weixin_44835297/article/details/111253150
2024-08-29 20:58:47