Category Archives: JavaScript

How to Solve pinia Error in ts File

Use Pinia in ts file report an error:

getActivePinia was called with no active Pinia. Did you forget to install pinia

 

1. Create the store.ts file

import { createPinia } from "pinia";

const store = createPinia();

export { store };

2、 Introduced in main.ts

import { createApp } from "vue";
import "./style.css";
import "./main.css";
import App from "./App.vue";
import ElementPlus from "element-plus";
import Avue from "@smallwei/avue";
import "@smallwei/avue/lib/index.css";
import "@/assets/css/mapbox-gl.css";
import { store } from "@/pinia/index";    // Introduce the created pinia
import router from "@/router/index";
import "element-plus/dist/index.css";

const app = createApp(App);

app.use(router);
app.use(store);  // use pinia
app.use(ElementPlus);
app.use(Avue);
app.mount("#app");

3、 Create your own Pinia file

import { defineStore } from "pinia";

interface State {
  nodeArr: any[] | [];
  stencilLoading: boolean;
  selectNodeId: number;
  lcNodeData: LCDataType | {}
}

const defaultState: State = {
  nodeArr: [], // Node data in the drag and drop bar
  stencilLoading: true, // Loading of the drag bar
  selectNodeId: -1, // The node id of the selected drag bar
  lcNodeData: {}, // The LC data in the selected canvas
};

export const lcDataStore = defineStore("lcData", {
  state: () => {
    return defaultState;
  },
  getters: {},
  actions: {},
});

4、 Using Pinia in the TS file

import { lcDataStore } from "@/pinia/lcAssign";
import { store } from "@/pinia/index";

const lcStore = lcDataStore(store);   // Here you have to pass in the store

// After that, you can use the properties and methods inside the lcStore

How to Solve npm-install Command -4048 Error

When I reinstall the computer system, I download the front-end environment configuration again. An error occurs when configuring NPM. The main error messages are as follows:

npm WARN logfile could not create logs-dir: Error: EPERM: operation not permitted, mkdir 'E:\work\node\node_cache\_logs'
npm WARN logfile could not be created: Error: ENOENT: no such file or directory, open 'E:\work\node\node_cache\_logs\2022-08-24T09_17_13_819Z-debug-0.log'
npm WARN logfile could not create logs-dir: Error: EPERM: operation not permitted, mkdir 'E:\work\node\node_cache\_logs'
npm WARN logfile could not be created: Error: ENOENT: no such file or directory, open 'E:\work\node\node_cache\_logs\2022-08-24T09_17_14_514Z-debug-0.log'
npm ERR! code EPERM
npm ERR! syscall mkdir
npm ERR! path E:\work\node\node_cache\_cacache
npm ERR! errno -4048
npm ERR! Error: EPERM: operation not permitted, mkdir 'E:\work\node\node_cache\_cacache'
npm ERR!  [Error: EPERM: operation not permitted, mkdir 'E:\work\node\node_cache\_cacache'] {
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: 'E:\\work\\node\\node_cache\\_cacache'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It's possible that the file was already in use (by a text editor or antivirus),
npm ERR! or that you lack permissions to access it.
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! Log files were not written due to an error writing to the directory: E:\work\node\node_cache\_logs
npm ERR! You can rerun the command with `--loglevel=verbose` to see the logs in your terminal

First, check whether the parameters of system environment configuration and user environment configuration are consistent

Click the path in the system environment configuration to observe whether the path is consistent. This may be my personal reason. After reinstalling node several times, the path here is inconsistent. After the change, it is still not possible.

I thought it was caused by the command line permission problem, and found that using the administrator still does not work, and then I searched the Internet for the reason and finally found it;

  1. Find the .npmrc file under C:\Users\{account}\ and delete it
  2. After clearing npm cache:npm cache clean –force
  3. Then run the npm install command.

[Solved] Uncaught SyntaxError: Invalid Unicode escape sequence

Page error encountered today: Uncaught SyntaxError: Invalid Unicode escape sequence

The parameter in the button click method is a software path, and an error will be reported when passing the parameter. The main reason is that the backslash in JS is caused by the escape character

So just replace the backslash with a double slash to solve the problem: replace(/\\/g,”/”)

[Solved] Element Error: Error in render: TypeError: dateStr.match is not a function“

This error is because the data type of the date component of Element cannot be Number

Solution: convert data to the string

number type to string type (recommended way two)
Method 1.
var date = toString(2022); // Disadvantage: can't convert underfind and null
Way 2
var date = String(2022); // can convert underfind and null
Way 3
var date = 2022 + ''; // string splicing    

[Solved] React Dependency Error: Invalid tag name “^np.0.2“ of package “react@^np.0.2“: Tags may not have an

When writing the carousel diagram, you need to install dependencies. Execute the following command. When you execute, you report an error, saying that it is a version problem. After you reduce the version of react, you search the Internet. Later, when you execute NPM install, you report various dependency errors

  npm install --save react-swipeable-views
    npm install --save react-swipeable-views-utils

The following is the error message: read the error message and say it is a problem with the version of the files in node_modules, but there is still an error after trying to change them. I can only ask you for advice.

the following is the package.json file

{
  "name": "react-goodlive-home",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/core": "^7.16.0",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
    "@svgr/webpack": "^6.3.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "babel-jest": "^27.4.2",
    "babel-loader": "^8.2.3",
    "babel-plugin-named-asset-import": "^0.3.8",
    "babel-preset-react-app": "^10.0.1",
    "bfj": "^7.0.2",
    "browserslist": "^4.18.1",
    "camelcase": "^6.2.1",
    "case-sensitive-paths-webpack-plugin": "^2.4.0",
    "css-loader": "^6.5.1",
    "css-minimizer-webpack-plugin": "^3.2.0",
    "dotenv": "^10.0.0",
    "dotenv-expand": "^5.1.0",
    "eslint": "^8.3.0",
    "eslint-config-react-app": "^7.0.1",
    "eslint-webpack-plugin": "^3.1.1",
    "file-loader": "^6.2.0",
    "fs-extra": "^10.0.0",
    "html-webpack-plugin": "^5.5.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.4.3",
    "jest-resolve": "^27.4.2",
    "jest-watch-typeahead": "^1.0.0",
    "mini-css-extract-plugin": "^2.4.5",
    "postcss": "^8.4.4",
    "postcss-flexbugs-fixes": "^5.0.2",
    "postcss-loader": "^6.2.1",
    "postcss-normalize": "^10.0.1",
    "postcss-preset-env": "^7.0.1",
    "prompts": "^2.4.2",
    "react": "^17.0.2",
    "react-app-polyfill": "^3.0.0",
    "react-dev-utils": "^12.0.1",
    "react-dom": "^17.0.2",
    "react-refresh": "^0.11.0",
    "react-router-dom": "^6.3.0",
    "resolve": "^1.20.0",
    "resolve-url-loader": "^4.0.0",
    "sass-loader": "^12.3.0",
    "semver": "^7.3.5",
    "source-map-loader": "^3.0.0",
    "style-loader": "^3.3.1",
    "tailwindcss": "^3.0.2",
    "terser-webpack-plugin": "^5.2.5",
    "web-vitals": "^2.1.4",
    "webpack": "^5.64.4",
    "webpack-dev-server": "^4.6.0",
    "webpack-manifest-plugin": "^4.0.2",
    "workbox-webpack-plugin": "^6.4.1"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "jest": {
    "roots": [
      "<rootDir>/src"
    ],
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jsdom",
    "transform": {
      "^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/config/jest/babelTransform.js",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "modulePaths": [],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ],
    "watchPlugins": [
      "jest-watch-typeahead/filename",
      "jest-watch-typeahead/testname"
    ],
    "resetMocks": true
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  },
  "devDependencies": {
    "less": "^4.1.3",
    "less-loader": "^6.0.0"
  }
}

Solution:

The dependent (@testing-library/react) version is relatively low, and it is useless. Just delete it and restart your computer.

Here is the package.json file after you solved the error

{
  "name": "@testing-library/jest-dom",
  "version": "5.16.5",
  "description": "Custom jest matchers to test the state of the DOM",
  "main": "dist/index.js",
  "engines": {
    "node": ">=8",
    "npm": ">=6",
    "yarn": ">=1"
  },
  "scripts": {
    "build": "kcd-scripts build",
    "format": "kcd-scripts format",
    "lint": "kcd-scripts lint",
    "setup": "npm install && npm run validate -s",
    "test": "kcd-scripts test",
    "test:update": "npm test -- --updateSnapshot --coverage",
    "validate": "kcd-scripts validate"
  },
  "files": [
    "dist",
    "extend-expect.js",
    "matchers.js"
  ],
  "keywords": [
    "testing",
    "dom",
    "jest",
    "jsdom"
  ],
  "author": "Ernesto Garcia <[email protected]> (http://gnapse.github.io)",
  "license": "MIT",
  "dependencies": {
    "@babel/runtime": "^7.9.2",
    "@types/testing-library__jest-dom": "^5.9.1",
    "aria-query": "^5.0.0",
    "chalk": "^3.0.0",
    "@adobe/css-tools": "^4.0.1",
    "css.escape": "^1.5.1",
    "dom-accessibility-api": "^0.5.6",
    "lodash": "^4.17.15",
    "redent": "^3.0.0"
  },
  "devDependencies": {
    "jest-environment-jsdom-sixteen": "^1.0.3",
    "jest-watch-select-projects": "^2.0.0",
    "jsdom": "^16.2.1",
    "kcd-scripts": "^11.1.0",
    "pretty-format": "^25.1.0"
  },
  "eslintConfig": {
    "extends": "./node_modules/kcd-scripts/eslint.js",
    "rules": {
      "@babel/no-invalid-this": "off"
    },
    "overrides": [
      {
        "files": [
          "src/__tests__/*.js"
        ],
        "rules": {
          "max-lines-per-function": "off"
        }
      }
    ]
  },
  "eslintIgnore": [
    "node_modules",
    "coverage",
    "dist"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/testing-library/jest-dom"
  },
  "bugs": {
    "url": "https://github.com/testing-library/jest-dom/issues"
  },
  "homepage": "https://github.com/testing-library/jest-dom#readme"
}

[Solved] electron-vue project error: Object.fromEntries is not a function electron-vue

electron-vue scaffold project build error: Object.fromEntries is not a function

Project directory

Front console print error:

Solution: install polyfill-object.fromentries and execute the command in the project root directory

npm i polyfill-object.fromentries

And then

import

import 'polyfill-object.fromentries';

[Solved] vite2+vue3 jsx Error: React is not defined

Vite2 + vue3 uses JSX to report an error: react is not defined

If JSX is not used in react, for error reporting:

React is not defined

It is required to add the following configuration to the vite.config.js file:

export default {
  esbuild: {
    jsxFactory: 'h',
    jsxFragment: 'Fragment',
    jsxInject: "import { h } from 'vue';"
  }
}

The last sentence is equivalent to the injection of vite. The helper automatically introduces h

[Solved] npm install Error: error code ERR_SOCKET_TIMEOUT

1. Error information

New project, Vue + element, NPM install, The error information reported at that time is as follows.

error code ERR_SOCKET_TIMEOUT
9673 error network Socket timeout
9674 error network This is a problem related to network connectivity.
9674 error network In most cases you are behind a proxy or have bad network settings.
9674 error network
9674 error network If you are behind a proxy, please make sure that the
9674 error network 'proxy' config is set properly.  See: 'npm help config'
9675 verbose exit 1
9676 timing npm Completed in 545124ms
9677 verbose unfinished npm timer reify 1661242562981
9678 verbose unfinished npm timer reify:unpack 1661242811008
9679 verbose unfinished npm timer reifyNode:node_modules/svgo 1661242811170
9680 verbose code 1

2. Solutions

//Step 1


npm install webpack webpack-cli --global



//Step 2
npm install rxjs



//Step 3
npm install webpack webpack-cli --global



//Finally, direct boot success
npm run dev 

 

[Solved] Vue2 Cross-domain Error: AxiosError net::ERR_FAILED, Network Error, ERR_NETWORK

Request scenario:

current page URL: http://127.0.0.1:8000/testcase
URL of jump request page: http://127.0.0.1:5000/testcase_orm
When using Axios request, the page prompts cross domain error

Cross-domain error reporting information

Access to XMLHttpRequest at ‘http://127.0.0.1:5000/testcase_orm’ from
origin ‘http://localhost:8080’ has been blocked by CORS policy: No
‘Access-Control-Allow-Origin’ header is present on the requested
resource.

AxiosError {message: ‘Network Error’, name: ‘AxiosError’, code:
‘ERR_NETWORK’

Screenshot of vue2 cross domain error report

through the analysis of the code and the error report information, the problem appears in the cross domain request (cross domain request: the browser does not allow the current source request to access another different source request. The source refers to the request agreement, domain name, and port number. If one of the three is inconsistent, it is a cross domain request)

current URL request URL Is it cross-domain Result analysis
http://www.kuakuakua.com http://www.kuakuakua.com/index.html no Same origin (the same domain name, protocol, and port number)
http://www.kuakuakua.com https://www.kuakuakua.com cross domain Different protocols (http/https)
http://www.kuakuakua.com http://www.javashuo.com/ cross domain Different domain names (www.kuakuakua.com/www.javashuo.com)
http://www.kuakuakua.com:8080 http://www.kuakuakua.com:8081 cross domain Different port numbers (8080/8081)

Solution

  • Step 1: Find the vue.config.js file in the project directory and open it for editing

insert image description here

  • Step 2: According to the structure in the figure, copy the given code to module.exports

insert image description here

devServer: {
    proxy: {
      "/proxy_url":{           // /proxy_url This is used to match with the root path baseURL
        target: 'http://127.0.0.1:5000', // this is to fill in the cross-domain request domain + port number, that is, the URL to request (does not include the URL path)
        changeOrigin: true, // whether to allow cross-domain requests, a virtual server will be created locally, then send the requested data, and receive the requested data at the same time, so that the server and the server to interact with the data will not have cross-domain problems
        pathRewrite: { // path rewrite
            '^/proxy_url': '/' // replace the request address in target, the original request is http://127.0.0.1:8000/kuayu the actual request is http://127.0.0.1:8000/proxy_url/kuayu  
        }
      }
    }
  }
  • Step 3: Find the main.js file and set axios.defaults.baseURL to /proxy_url
axios.defaults.baseURL = ‘/proxy_url’
  • Step 4: Then the axios request in the methods in the xxx.vue file can be used normally. The complete request URL here is http://127.0.0.1:5000/testcase_orm (Step 4 is just to provide an example, the specific request URL Request according to the URL of your own project)
methods:{
    getCaseList: function(){
        console.log("xxxxxxxxx")
        console.log('Check if the interface call is successful')
        this.$axios.get('/testcase_orm').then((result)=>{
             console.log('Check if the interface call is successful, if it is called, it is successful')
             console.log(result)
        })
    }
  }

Solution Analysis.
Cross-domain problem, you can let the server to add the request header field information and allow cross-domain access, the server-side cross-domain problem is not described in this article, interested to see another Django cross-domain problem solving blog post

The vue cross domain problem is solved by using a proxy solution, which is forwarded to the target server through a proxy on the local server, so that the cross domain is only for the browser, and the cross domain problem does not occur for requests sent by the node service, thus solving the browser cross domain problem.

[Solved] Echarts Error: TypeError: Cannot read properties of null (reading getAttribute )

The above problem was encountered when using echarts

Generally, there are the following cases.
1. echarts.init(document.getElementById("xxxx") is written in the wrong format, such as adding a # in front of the id.

2. initialize operation when the element is not loaded out (stack a debugger on top of the initialized code to easily determine). Here specifically in vue.

If an error is reported you can put the code inside mounted.
mounted() {    
	this.initEcharts();   
}

Differences between mounted and created:

created:Called before the template is rendered into html, applied to initialize some attribute values and then rendered into view requirements.
mounted:Called after the template is rendered into html, to initialize the page and then perform some operations on the dom nodes of the html after it is finished.

[Solved] Error in nextTick: “TypeError: undefined is not iterable

Error in nextTick: “TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))”


The parent component did not pass the corresponding parameter Found:

<label-template
   :image-list="checkImageList"
   :tag-list="tagList"
   @onAllFeatures="onAllFeatures"
   :active-tab="activeTab"
   @next-page="nextPage"
   @previous-page="previousPage"
 />
historicalList.length //The parent component does not pass list, but the child component uses it and gets the length