Category Archives: JavaScript

Vue Error: Error in v-on handler (Promise/async): “Error: Error“

The error message is as follows

[Vue warn]: Error in v-on handler (Promise/async): "Error: Error"

found in

---> <Navbar> at src/layout/components/Navbar.vue
       <Layout> at src/layout/index.vue
         <App> at src/App.vue
           <Root>

The solution is as follows

1. F12 enter the developer mode and click the area in the box

2. Check the response code, which is the value on the right side of res.code

3. Add code to easy mock

“Failed to load resource: net::ERR_FILE_NOT_FOUND” error. The project created by vue-cli 3.0 can run under dev, and an error is reported after packaging, and the page is blank.

Cli3.0 Solutions:
Failed to Load Resource: net::ERR_FILE_NOT_FOUND
Dist /index.html, the introduction is problematic,

The webPack configuration file cannot be found in the project created by Ue-CLi 3.0, because it is encapsulated by Ue-CLi 3.0. You only need to modify it in the vue.config.js file in the root directory of the project (if the project does not have this file, add one directly in the root directory), and set the baseUrl value to ‘./ ‘, and modify as follows

const webpack = require("webpack");
module.exports = {
    pluginOptions: new webpack.ProvidePlugin({
        jQuery: "jquery",
        $: "jquery"
    }),
    baseUrl: './' // ADD these codes
};

Cli2.x Solutions:
Open config/index.js file and build-> AssetsPublicPath is changed to “./ “, which is preceded by a dot.

build: {
  // Template for index.html
  index: path.resolve(__dirname, '../dist/index.html'),

  // Paths
  assetsRoot: path.resolve(__dirname, '../dist'),
  assetsSubDirectory: 'static',
  assetsPublicPath: './',  // Here
}

Ok, 2. X 3.0 is all done
Please indicate the source of the reprint

JS bug Log Uncaught TypeError: Cannot read property ‘previoustSibling‘ of null

The program code is:

 <!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Visit the Dangdang shopping cart page node</title>
    <link type="text/css" rel="stylesheet" href="css/cartStyle.css" />
</head>
<body>

<div class="content">
    <div class="logo">
        <img src="images/dd_logo.jpg"><span onclick="close_plan();">close</span>
    </div>
    <div class="cartList" id="cartList">
        <ul>
            <li>¥<input type="text" name="price" value="21.90"></li>
            <li><input type="button" name="minus" value="-" onclick="minus(0);"><input type="text" name="amount" value="1"><input type="button" name="plus" value="+" onclick="plus(0);"></li>
            <li id="price0">¥21.90</li>
            <li><p  onclick="collection();">add</p><p onclick="del();">del</p></li>
        </ul>
        <ul>
            <li>¥<input type="text" name="price" value="24.00"></li>
            <li><input type="button" name="minus" value="-" onclick="minus(1);"><input type="text" name="amount" value="1"><input type="button" name="plus" value="+" onclick="plus(1);"></li>
            <li id="price1">¥24.00</li>
            <li><p  onclick="collection();">add</p><p onclick="del();">del</p></li>
        </ul>
        <ol>
            <li id="totalPrice">&nbsp;</li>
            <li><span onclick="accounts()">payout</span></li>
        </ol>
    </div>
    <div id="money"></div>
</div>
<script type="text/javascript" src="js/shopping.js">


</script>
<script type="text/javascript">
	function accounts(){
	     var num1=document.getElementById("cartList").firstChild.lastChild.previoustSibling.innerHTML;
		 var num2=document.getElementById("cartList").firstChild.nextSibling.lastChild.previousSibling.innerHTML;
		 var num3=document.getElementById("totalPrice").innerHTML;
		 var num4="Information about your current purchase is as follows:<br/>White Rock:White says: "+num1+"<br/>Island Bookstore: "+num2+"<br/>Total items:"+num3;
		 document.getElementById("money").innerHTML=num4;
	    }
</script>
</body>
</html>

Display error:

Uncaught TypeError: Cannot read property 'previoustSibling' of null
    at accounts (shopping.html:39)
    at HTMLSpanElement.onclick (shopping.html:29)

Error reason: unable to read space

Solution:
add element to the get node in function accounts()

The correct function code is:

function accounts(){
	     var num1=document.getElementById("cartList").firstElementChild.lastElementChild.previousElementSibling.innerHTML;
		 var num2=document.getElementById("cartList").firstElementChild.nextElementSibling.lastElementChild.previousElementSibling.innerHTML;
		 var num3=document.getElementById("totalPrice").innerHTML;
		 var num4="Information about your current purchase is as follows:<br/>White Rock:White says: "+num1+"<br/>Island Bookstore: "+num2+"<br/>Total items:"+num3;
		 document.getElementById("money").innerHTML=num4;
	    }

TypeError: r.indexOf is not a function TypeError: r.indexOf is not a function

After checking some data, it was found that the data was passed from the back end to the front end, and the front end did not handle it well, so an error was reported

Problem: because I want to load a list El table, the required data format is as follows

// Required data format for el-table's :data
[{...} ,{...} ,... ,{...}]
// The format of the data returned by the backend, I returned it directly to :data, which is obviously not correct, it should wrap a []
{...}

Based on this, the way of processing data is not right

// For example, if you deconstruct a res object from the backend, you only need [res] or [res.xx] to solve the problem
// Instance:
getUserByName(name).then(res => {
	console(res) // you can look at the format of res in the background, what you really want, and then take it out by way of .xxx
	this.userList = [res.data]
})
// I'll go back to el-table here and put :data=userlist to fix it

[Vue Run Error] Module build failed: Error: Couldn‘t resolve parser “babylon“

This is because the parser names of different versions of prettier are not the same, so it cannot be parsed. You just need to   node_ Modules in Vue loader   The parser in the prettier configuration file can be changed from Babylon to Babel.

Step 12345 as shown in the figure below

SwiftUI 2.0: How to Import Files into iOS Apps

Task

I wanted to import an audio file into an iOS 14.0 or later app built using Swift UI 2.0 at work, but I had problems with security-scoped URL s and styling, so I wanted to share my experience …

File picker

With the release of iOS 14 Beta 6, Apple has provided a new view qualifier that allows users to import existing files from their iOS device or iCloud Drive . First, fileImporter()let’s check out this new modifier …

fileImporterModifier

fileImporter(isPresented:allowedContentTypes:allowsMultipleSelection:onCompletion:)The method allows the user to import one or more files.

Declaration
SwiftUI
func fileImporter(
    isPresented: Binding<Bool>, 
    allowedContentTypes: [UTType], 
    allowsMultipleSelection: Bool, 
    onCompletion: @escaping (Result<[URL], Error>) -> Void
) -> some View
parameter
  • isPresented : A binding that supports whether to display the file picker interface.
  • allowedContentTypes : A list of supported content types that can be imported .
  • allowsMultipleSelection : A Boolean value that supports whether the user can select and import multiple files at the same time.
  • onCompletion : A callback that will be called when the operation is successful.
Details
  • To display the file picker , set the isPresentedvariable bound with to true .
  • When the file to import is selected onCompletionisPresentedis automatically set back to false before the callback is called .
  • If the user cancels the import, isPresentedis automatically set back to false and the onCompletioncallback is not called.
  • onCompletionWhen the callback is invoked, resultteeth .successor .failurebe either.
  • .successIf, contains a list resultof URLs of files to import .
Note

allowedContentTypesCan be changed
as soon as the file importer is displayed, but has no immediate effect and is only applied the next time the file importer is displayed.

Sample code

Let’s test the implementation code by importing and playing one audio file:

SwiftUI
import SwiftUI
import AVFoundation
...
    @State private var isImporting = false
    var body: some View {
        Button(action: {
            isImporting = true
        }) {
        Image(systemName: "waveform.circle.fill")
            .font(.system(size: 40))
        }
        .fileImporter(
            isPresented: $isImporting,
            allowedContentTypes: [.audio],
            allowsMultipleSelection: false
        ) { result in
            if case .success = result {
                do {
                    let audioURL: URL = try result.get().first!

                    let audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
                    audioPlayer.delegate = ...
                    audioPlayer.prepareToPlay()
                    audioPlayer.play() // ← ERROR raised here

                } catch {
                    let nsError = error as NSError
                    fatalError("File Import Error \(nsError), \(nsError.userInfo)")
                }
            } else {
                print("File Import Failed")
            }
        }
    }
...

what happened? !!

error

Below is the error I got in the XCode console when I ran the code for the actual implementation:

XCode
2021-04-23 10:00:01.123456+0900 MyApp[10691:1234567] Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
2021-04-23 10:00:01.123456+0900 MyApp[10691:1234567] Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
Playback initialization for "file:///private/var/mobile/Containers/Shared/AppGroup/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/File%20Provider%20Storage/Voice/TestFile.m4a" file has failed: Error Domain=NSOSStatusErrorDomain Code=-54 "(null)".
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file MyApp/AudioPlayer.swift, line 123

Meaning of error

Apps on iOS are sandboxed and access to files inside the sandbox is unlimited , but access to files outside the sandbox is restricted without proper permissions .

How do I get permissions to access files outside the app’s sandbox?

Security authority

Once you have a list of URLs for the files you want to import, you need to get permissions to access them.

startAccessingSecurityScopedResource() Method

Declaration
Swift
func startAccessingSecurityScopedResource() -> Bool
Return value

This function returns true if the request to access the file was successful , false otherwise.

Details

Once you get the security scope URL, you can’t immediately use the file it points to.

To access the file, you need to call a startAccessingSecurityScopedResource()method (or Core Foundation equivalent CFURLStartAccessingSecurityScopedResource(_:)function) at the security scope URL, which adds the file location to your app’s sandbox and makes the file available to your app. ..

After successfully gaining access to a file, you should give up access to the file as soon as you finish using it.

As a result, calling a stopAccessingSecurityScopedResource()method (or its equivalent Core Foundation equivalent CFURLStopAccessingSecurityScopedResource(_:)) in a URL relinquishes access and immediately makes the file inaccessible.

Note

If you don’t give up access when file system resources are no longer needed, your app will leak kernel resources. If a lot of kernel resources are leaked, the app will not be able to add the file system location to the sandbox until it is restarted.

Sample code
SwiftUI
...
    @State var audioFiles: Array<MediaFileObject> = Array<MediaFileObject>()
    @State private var isImporting = false
    var body: some View {
        Button(action: {
            isImporting = true
        }) {
        Image(systemName: "waveform.circle.fill")
            .font(.system(size: 40))
        }
        .fileImporter(
            isPresented: $isImporting,
            allowedContentTypes: [.audio],
            allowsMultipleSelection: false
        ) { result in
            if case .success = result {
                do {
                    let audioURL: URL = try result.get().first!
                    if audioURL.startAccessingSecurityScopedResource() {
                        audioFiles.append(AudioObject(id: UUID().uuidString, url: audioURL))
                    }
                } catch {
                    let nsError = error as NSError
                    fatalError("File Import Error \(nsError), \(nsError.userInfo)")
                }
            } else {
                print("File Import Failed")
            }
        }
    }
...

File type

Shared system data formats can be used for resources to load, save, and open from other apps . Alternatively, you can define your own files and data formats as needed .

In my code, it represents all kinds of audio files, belong to the category “image, audio, and basic type of video” .audiousing the type;

  • image : A basic type that represents image data.
  • audio : A type that represents audio that does not contain video.
  • audiovisualContent : A basic type that represents data that contains video content that may or may not contain audio.
  • movie : A basic type that represents a media format that may contain both video and audio.
  • video : A type that represents a video that does not contain audio.

styling

With SwiftUI 2.0 (expecting SwiftUI 3.0), styling isn’t really easy yet, but I’ve found some ways to change the look of the file picker:

  • UINavigationBar.appearance().tintColor: UIColor: The color of the toolbar item in the header of the file picker.
  • UITabBar.appearance().barTintColor: UIColor: The background color of the tab bar at the bottom of the file picker.
  • UITabBar.appearance().tintColor: UIColor: The color of the currently selected tab bar item.
  • UITabBar.appearance().unselectedItemTintColor: UIColor: The color of the toolbar item that is not currently selected.

be careful ! Using UIKit settings in this way can affect the appearance of the navigation bar and tab bar in other parts of the application.

At the end

We hope this article helps you implement file imports in your app.

How to do SwiftUI 1.0?

I tried to implement a file picker that imports ( fileImporter()none) audio files in another way, but I couldn’t!

fileExporterModifier

fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)The method allows the user to export a document in memory to a file on disk.

fileMoverModifier

fileMover(isPresented:file:onCompletion:)The method allows the user to move an existing file to a new location.

The vue3 project Error: Cannot find module’vue-loader-v16/package.json’

In the past two days, I plan to learn vue3. The build project does not use vite, but builds it through vue cli. The vue cli building vue3 project is similar to the previous vue2, but vue cli needs to be upgraded to the latest version.

After the newly generated project, run an error:

Error: Cannot find module'vue-loader-v16/package.json'

Here is the tutorial on how to solve this problem here:

 

1. Upgrade npm

npm i -g npm

Those who use cnpm should also upgrade cnpm

cnpm i -g cnpm

 

2. Reinstall the node_modules dependency package

rm- rf node_modules // delete the original dependency package first

cnpm i // reinstall

 

3. Re-download

cnpm i -D vue-loader-v16

 

Then you can successfully run the project. . .

The solution to the problem that the custom styles of UI components such as element-ui in the vue project do not take effect

Although the default style has been able to meet many needs when usingelement-ui, there are always some custom needs to be added sometimes. However, sometimes the style is written on it, which should be correct in theory, but it does not take effect.
In fact, when vueusing a third-party framework in a project, this problem may occur. The reason is vuethat it scopedcan be declared that the style is effective within the scope of the component. So as to avoid style pollution of different components, but most people write with scopedthem, so the style scopeddoes not take effect in the domain.
Solution:

1. Remove scoped

Directly <style lang="less" scoped>in scopedto remove it so that style to take effect, although simple and crude but it is not a good method.

2. Use deep action selectors

Used >>>as a deep-action selector in css

<style scoped>
 .box >>> .el-input {
   width: 60px;
 }
 </style>

Used /deep/as a deep-action selector in less

<style lang= "less" scoped>
 .avatar-uploader /deep/ .el-upload {
   border: 1px dashed #
   d9d9d9; border-radius: 6px;
   cursor: pointer;
 }
 </style>

 

3. Use global styles

Define a global style, such as global.css, and then main.jsimport it in, so that this style is globally mounted, and the custom styles written in it will also take effect.

Error: Computed property “menuList” was assigned to but it has no setter.

Here is a simple method on how to solve error: Computed property “menuList” was assigned to but it has no setter.

1
2
3
4
5
6
7
8
9
10
11
12
// How to Solve
computed: {
  heandletState: {
    get() {
      return this.$store.getters.heandletState;
    },
    // Write it out not to achieve
    set(val) {
      console.log("vid", val);
    }
  }
},

Docker Quickstart Terminal Error: No default Boot2Docker ISO found locally

(default) No default Boot2Docker ISO found locally, downloading the latest release…
Error with pre-create check: “Get https://api.github.com/repos/boot2docker/boot2docker/releases/latest: read tcp 172.16. 4.109:51024->13.250.168.23:443: wsarecv: An existing connection was forcibly closed by the remote host.”
Looks like something went wrong in step ´Checking if machine default exists´… Press any key to continue… A

 

 

 

You can go to GitHub to find  boot2docker.iso    under Thunder, put it under C:\Users\xxxxx\.docker\machine\cache\ and reopen Docker Quickstart Terminal

The body of a for-in should be wrapped in an if statement to filter unwanted properties from the pro

In ESLint mode, for in will report an error when traversing the object, which can be solved as follows:

let  val  = { shu: [ 1 , 2 , 3 ]} ;
for  (let  item  in  val) {
  if  (val.hasOwnProperty(item)) { 
    console.log(item);
  }
}

Because we should judge whether the object has its own properties (non-inheritance) before traversing an object. If the object is an empty object, then there is no need to traverse it to improve the efficiency of the code.