[Vue] Modifiers, form submission methods, key steps for custom components

Welcome to my CSDN homepage!

I am Java Fang Wenshan, a blogger who shares notes on CSDN.

Recommend to everyone my column “Vue Quick Start”.

Click here to view my homepage!

Java Fang Wenshan’s personal homepage

If you feel good, please give me a like!

Looking forward to your joining, learning and making progress together!

Please add image description

Table of Contents

1. Modifier

1.1.Event modifiers

1.1.1.stop

1.1.2.prevent

1.1.3.capture

1.1.4.self

1.1.5.once

1.2.Key modifier

1.2.1enter

1.2.2.tab

1.2.3.delete

1.2.4.esc

1.2.5.space

1.2.6 .up, .down, .left, .right

1.2.7 .ctrl, .alt, .shift, .meta

2. Form

2.1. Binding value and value acquisition

2.2. Effect demonstration

3. Custom components

3.1. Local components

3.1.1. Component passing parameters (from parent to child)

3.1.2. Component passing parameters (son to parent)

3.2.Global components


1. Modifier

1.1.Event modifier

Event handler? Special suffix (.) used to indicate that a directive should be bound in a special way. Commonly used modifiers in Vue include: v-on, v-model, v-if, v-for, v-bind, etc. For example, v-on:click is an event handler that fires when the user clicks on an element. If you need to prevent the default behavior, you can use the .prevent modifier.

1.1.1.stop

In Vue, when an event is fired, it bubbles up to the parent element. If the parent element also has the same event handler, the event handler will be fired again. To stop this event from bubbling up, we can use the .stop modifier.

<div @click="outerClick">
  <button @click.stop="innerClick">Click me</button>
</div>

In this example, when the user clicks the button, only the innerClick method is triggered, but not the outerClick method.

1.1.2.prevent

The .prevent modifier is used to prevent the default behavior of an event.

<a href="https://www.example.com" @click.prevent="handleClick">Click here</a>

In this example, when the user clicks on the link, the browser will jump to the specified URL by default. However, since we are using the .prevent modifier, this default behavior will be prevented.

1.1.3.capture

The .capture modifier is used to handle events in the capture phase rather than the bubbling phase.

<div @click.capture="outerClick">
  <button @click.capture="innerClick">Click me</button>
</div>

In this example, when the user clicks the button, the event handler is fired during the capture phase, not the bubbling phase. This means that even if the parent element also has the same event handler, it will not be fired.

1.1.4.self

The .self modifier is used to bind event handlers to the current element itself, rather than its child elements.

<div @click.self="outerClick">
  <button @click.self="innerClick">Click me</button>
</div>

In this example, when the user clicks on the button, the outerClick method will only be triggered when the button is clicked. If the button is clicked but is not fully focused (for example, when the user clicks on the button’s text), no methods will be triggered.

1.1.5.once

The .once modifier is used to ensure that the event handler is only triggered once.

<button @click.once="handleClick">Click me</button>

In this example, the handleClick method will only be triggered once when the user clicks the button, and will not be triggered again even if the button is clicked multiple times.

Note 1: What is event bubbling?

When we click on the top div, the click event is triggered. However, as the bubbling event propagates, the click event of the div below the div will also be triggered. This is the bubbling event propagation.

1.2.Key modifier

Usually used in JavaScript to handle user keyboard input.

1.2.1enter

This modifier is typically used to handle “Enter” key events. For example, when a user presses the “Enter” key in an input box, we can perform actions such as submitting a form or starting a search.

document.querySelector('input').addEventListener('keydown', function(event) {
  if (event.key === 'Enter') {
    console.log('Enter key pressed');
  }
});

1.2.2.tab

This modifier is typically used to handle “Tab” key events. For example, when the user presses the “Tab” key in the input box, we can move the focus to the next editable element.

document.querySelectorAll('input, button').forEach(function(element, index) {
  element.addEventListener('keydown', function(event) {
    if (event.key === 'Tab') {
      // Move to next element if it's not the last one
      if (index <this.length - 1) {
        this[index + 1].focus();
      }
    }
  });
});

1.2.3.delete

This modifier is typically used to handle “Delete” key events. For example, when the user presses the “Delete” key in the input box, we can delete the entered content.

document.querySelector('input').addEventListener('keydown', function(event) {
  if (event.key === 'Delete') {
    event.preventDefault(); // Prevent the default action of deleting text
    console.log('Delete key pressed');
  }
});

1.2.4.esc

This modifier is typically used to handle “Esc” key events. For example, when the user presses the “Esc” key in the input box, we can cancel the current operation or close the window.

document.querySelector('input').addEventListener('keydown', function(event) {
  if (event.key === 'Escape') {
    console.log('Escape key pressed');
  }
});

1.2.5.space

This modifier is typically used to handle “Space” key events. For example, when the user presses the “Space” key in the input box, we can trigger a function or perform an action.

document.querySelector('input').addEventListener('keydown', function(event) {
  if (event.key === ' ') {
    console.log('Space key pressed');
  }
});

1.2.6 .up, .down, .left, .right

These modifiers are typically used to handle arrow key events. For example, when the user presses the arrow keys in the input box, we can move the cursor to a position up, down, left, or right.

document.querySelector('input').addEventListener('keydown', function(event) {
  if (event.key === 'ArrowUp') {
    console.log('Up arrow key pressed');
  } else if (event.key === 'ArrowDown') {
    console.log('Down arrow key pressed');
  } else if (event.key === 'ArrowLeft') {
    console.log('Left arrow key pressed');
  } else if (event.key === 'ArrowRight') {
    console.log('Right arrow key pressed');
  }
});

1.2.7 .ctrl, .alt, .shift, .meta

These modifiers are typically used to handle events for special keys. For example, when the user presses the Ctrl, Alt, Shift or Meta key in the input box, we can perform some special operations.

document.querySelector('input').addEventListener('keydown', function(event) {
  if (event.ctrlKey) {
    console.log('Ctrl key pressed');
  }
  if (event.altKey) {
    console.log('Alt key pressed');
  }
  if (event.shiftKey) {
    console.log('Shift key pressed');
  }
  if (event.metaKey) {
    console.log('Meta key pressed');
  }
});

The above modifiers are not all. If you are interested, you can go to the official website to check the relevant information! !

2. Form

2.1. Binding value and value

In order to demonstrate the effect, I will not explain the binding value and the value separately, just look at the code! ! !

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form</title>
</head>
<h2>Form assignment and value acquisition</h2>
<div id="app">
<form :model="form" @submit.prevent="submit">
<div>
User: <input v-model="form.username" placeholder="Please enter username">
</div>
<div>
Password: <input v-model="form.password" placeholder="Please enter password" type="password">
</div>
<div>
<label>Avatar<input type="file" @change="handleChange"></label>
</div>
<div>
Name: <input v-v-model.trim="form.name" placeholder="Please enter your real name">
</div>
\t\t\tgender:
<span v-for="sexs in sexList">
<input v-model="form.sex" type="radio" name="sex" :value="sexs.id">{<!-- -->{sexs.name}}
</span>
<div>
Age: <input v-model.number="form.age" type="number" placeholder="Please enter your age">
</div>
\t\t\tHobby:
<span v-for="h in hobby">
<input type="checkbox" v-model="form.hobbies" :value="h.id" />{<!-- -->{h.name}}
</span>
\t\t\t
<div>
Campus:
<select v-model="form.campus">
<option v-for="addr in address" :value="addr.id">{<!-- -->{addr.name}}</option>
</select>
</div>
<div>
\t\t\t\tpersonal information:
<textarea v-model.lazy="form.other" style="vertical-align: middle;" cols="30" rows="10"></textarea>
</div>
<div>
<input v-model="form.accept" type="checkbox">
Read and accept <a href="https://blog.csdn.net/weixin_74318097?spm=1011.2415.3001.5343">"User Agreement"</a>
</div>
<button>Submit</button>
</form>
</div>

<script src="//i2.wp.com/cdn.jsdelivr.net/npm/vue@2"></script>
<script>
newVue({
el: '#app',
data() {
return {
form: {
hobbies: []
},
image: {},
sexList:[{
id:1,name:"Female"
},{
id:2,name:"Male"
},{
id:3,name:"Unknown"
}],
hobby: [{
id: 1,
name: 'basketball'
}, {
id: 2,
name: 'football'
}, {
id: 3,
name: 'chess'
}],
address: [{
id: 1,
name: "Shanghai"
}, {
id: 2,
name: "Shenzhen"
}, {
id: 3,
name: "Hangzhou"
}, {
id: 4,
name: "Hunan"
}]
}
},
methods: {
submit() {
console.log(this.form);
},
handleChange(event) {
let file = event.target.files[0]
this.form.image = file
}
}
})
</script>
</html>

There are a few things to note about the above code:

1. Model=”form” appears in the

tag. This is to dynamically collect various data in the form into the form object in vue’s data to facilitate unified management.

2. @submit.prevent on the form tag is the default behavior (jump) to prevent the form from being submitted.

3.v-model.trim is to remove the spaces before and after the input data; v-model.number is to convert it to Number type;

v-model.lazy renders data to the page after losing focus.

4. If our hobby attribute does not define a variable or defines null or {}, one will be selected and all will be selected.

5. When we assign Value, do not write value directly because Vue cannot capture it. You need to write: value

2.2. Effect demonstration

Let’s take a look at the obtained value.

The value has also been obtained in the console. When the time comes, our backend will definitely receive data in JSON format. This is enough.

3. Custom components

In JavaScript, custom components are often called custom elements rather than custom tags. A custom element is an HTML element that allows you to create reusable code snippets that can be used across multiple pages. Custom elements are part of the Web Components specification, and they allow you to combine HTML, CSS, and JavaScript to create reusable components.

The syntax of custom components is similar to filters, so it also has local components and global components.

3.1.Local component

<my-button >123<my-button>

This is a custom component but it has not been associated with Vue, so the output on the page is only 123. I will associate it below.

<script>
newVue({
el: '#app',
components: {
"my-button": {
template: "<button>Custom component</button>"
}
}
})
</script>

What is displayed on the page is the button.

3.1.1. Component passing parameters (from father to son)

<div id="app">
<my-button name="I am Laozi"><my-button>
</div>

<script src="//i2.wp.com/cdn.jsdelivr.net/npm/vue@2"></script>
<script>
newVue({
el: '#app',
components: {
"my-button": {
props:['name'],
template: "<button>{<!-- -->{name}}</button>"
},
}
})
</script>

Receive the attributes on the custom tag through props and assign them to the content that needs to be displayed on the page by the custom component.

3.1.2. Passing parameters from component (passing from son to parent)

<div id="app">
<my-button name="我老子" n="1"><my-button>
</div>

<script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script>
newVue({
el: '#app',
components: {
"my-button": {
props:['name'],
//template represents the class content of the custom component displayed on the page
template:'<button @click="incrn">I was beaten {<!-- -->{n}} times by {<!-- -->{name}}</button>',
data:function(){
return {
n:1
}
},
methods:{
incrn(){
this.n + + ;
}
}
}
}
})
</script>

In Vue, the parent component passes data to the child component through prop. If you want to pass the data of the child component to the parent component, you can bind the custom event.

Summary:

Parent Vue instance->Vue instance, pass data through prop

Child Vue instance->parent Vue instance, passing data through events

3.2.Global Component

<script type="text/javascript">
Vue.component('my-button', {
// props are used to define variables in components
props:['m'],
//template represents the class content of the custom component displayed on the page
template:'<button v-on:click="incrn">I was clicked {<!-- -->{m}} {<!-- -->{n}} times</button>',
data:function(){
return {
n:1
}
},
methods:{
incrn(){
this.n + + ;
}
}
});
\t\t
</script>

This is the definition of the global component, and the effect will not be displayed the same as above.

Please add image description

My sharing ends here. Welcome to the comment area to discuss and exchange! !

If you find it useful, please give it a like