Table of contents
Several commonly used event modifiers:
1. Style binding
- Class binding
Usage: v-bind:, expression type: string, array, object - style binding
v-bind:style="expression", the type of expression: string, array, object
Example:
<!--定义示例样式-->
<style>
.fontClass {
font-size: 40px;
}
.colorClass {
color: red;
}
</style>
<div id="app">
<p><span v-bind:class="fc">aaaaa</span></p>
<p><span v-bind:class="ac">aaaaa2</span></p>
<p><span :style="myStyle">aaaaa3</span></p>
</div>
var vm = new Vue({
el: '#app',
data: {
fc: 'fontClass',
ac: ['fontClass', 'colorClass'],
fontSize: 40,
color: 'green',
//样式对象,注意:样式名使用驼峰命名,如:fontSize
myStyle: {
fontSize: '50px',
color: 'red',
fontWeight: 'bold'
}
}
});
Show results
2. Event modifier
Several commonly used event modifiers:
<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>
<!-- click 事件只能点击一次 -->
<a v-on:click.once="doThis"></a>
<!-- 阻止单击事件冒泡 -->
<a v-on:click.stop="doThis"></a>
<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- 添加事件侦听器时使用事件捕获模式 -->
<div v-on:click.capture="doThis">...</div>
Example:
<div id="app">
<div>接收消息:{
{receverMsg}}</div>
<p>
<!--响应多次或一次点击事件-->
<input type="text" v-model="sendMsg">
<button @click="sender">发送(多次)</button>
<button @click.once="sender">发送(一次)</button>
</p>
<p>
<!-- 阻止表单提交 -->
<form action="testAction.action" method="post" @submit.prevent="doSubmit()">
<label>名称</label>
<input type="text" name="name" />
<input type="submit" value="提交" />
</form>
</p>
<!-- 案件修饰符 -->
<p>
<input v-model:value="val" v-on:keyup.13="keyup" />
</p>
</div>
var vm = new Vue({
el: '#app',
data: {
receverMsg: null,
sendMsg: null,
val: null
},
methods: {
sender: function() {
this.receverMsg = this.sendMsg;
},
doSubmit: function() {
alert('ok');
},
keyup: function() {
alert(this.val);
}
}
});
Show results
Press the Enter key to directly pop up the prompt
3. Key modifiers
Vue allows adding key modifiers for v-on when listening for keyboard events.
Example:
<!-- Only call vm.submit() if keyCode is 13 -->
<input v-on:keyup.13="submit">
<!-- Use the following to have the same effect-->
<input v-on:keyup.enter="submit">
key alias | meaning |
---|---|
.enter | Enter to confirm |
.tab | TAB key |
.delete | Capture "Delete" and "Backspace" keys |
.esc | The Esc key in the upper left corner of the keyboard, the cancel key |
.space | space bar |
.up | superior |
.down | Down |
.left | left |
.right | right |
.ctrl | ctrl key |
.shift | shift key |
Example: Responding to enter event
<input type="text" @keyup.13="doSubmit" v-model="name">
var vm = new Vue({
el: "#app",
data: function() {
return {
name: 'hello vue'
}
},
methods: {
doSubmit: function() {
alert("响应enter," + this.name);
}
}
});
4. Common controls
4.1 Example
Familiarize yourself with commonly used controls by implementing a type registration page. Text box/password box/text field/single selection/multiple selection/drop-down list
<div>
<label>账号:</label>
<input type="text" v-model="uname">
</div>
<div>
<label>密码:</label>
<input type="password" v-model="upwd">
</div>
<div>
<label>年龄:</label>
<input type="text" v-model="age">
</div>
<div>
<label>性别:</label>
<input type="radio" v-model="sex" value="1">男
<input type="radio" v-model="sex" value="2">女
</div>
<div>
<label>爱好</label>
<div v-for="h in hobbies">
<input v-model="hobby" type="checkbox" :value="h.id" />{
{h.name}}
</div>
</div>
<div>
<label>地区</label>
<select v-model="selectedCity">
<option value="">-- 请选择 --</option>
<option v-for="c in city" :value="c.id">{
{c.name}}</option>
</select>
</div>
<div>
<label>备注:</label>
<textarea v-model="remark"></textarea>
</div>
<div>
<input type="checkbox" v-model="agreed">是否已阅读并同意协议
</div>
Simple way without using monitor: remove the monitor, then modify the submit button as follows
<div> <button @click="submit" :disabled="disabled">提交</button> </div>
var vm = new Vue({
el: '#app',
data: {
uname: '',
upwd: '',
age: '',
sex: 1,
//用于通过v-for指令输出多选框列表
hobbies: [{
id: '1',
name: '打游戏'
},
{
id: '2',
name: '编程'
},
{
id: '3',
name: '旅游'
}
],
hobby: [],
//用于生成地区选择列表
city: [{
id: "1",
name: "长沙"
},
{
id: "2",
name: "株洲"
},
{
id: "3",
name: "湘潭"
}
],
//用于保存用户选择的地区
selectedCity: '',
// 用于保存备注
remark: '',
//是否同意协议,默认值为false
agreed: false,
//提交按钮是否禁用,默认为true
disabled: true
},
methods: {
sender: function() {
this.receverMsg = this.sendMsg;
},
doSubmit: function() {
alert('ok');
},
keyup: function() {
alert(this.val);
},
submit: function() {
let data = {
uname: this.uname,
upwd: this.upwd,
age: this.age,
sex: this.sex,
hobby: this.hobby,
city: this.selectedCity,
remark: this.remark
}
console.log(data);
}
},
watch: {
agreed: function(val) {
if (val) {
this.disabled = false;
} else {
this.disabled = true;
}
}
}
});
Show results:
4.2 Modifiers
modifier | effect |
---|---|
.lazy | By default, v-model synchronizes the value of the input box with the data in the input event, but you can add a modifier lazy to switch to synchronization in the change event |
.number | Convert the user's input value to Number type |
.trim | Automatically filter leading and trailing spaces entered by the user |
Take .number as an example to illustrate the use of modifiers to convert the entered age attribute to a numeric type
<div>
<label>年龄:</label>
<input type="text" v-model.number="age" >
</div>
5. Custom instructions
In addition to supporting built-in instructions such as v-model/v-show, Vue also allows custom instructions. In vue2, the main form of code reuse and abstraction is components, but in some cases, it is still necessary to perform low-level operations on common DOM elements. In this case, custom instructions are required . According to the scope of the custom instruction, it can be divided into two types: global and local
local
Set text color by custom label
<div id="app">
<!--red绑定到data里面的变量-->
<p v-color="red">我是自定义指令</p>
</div>
var vm = new Vue({
el: '#app',
data: {
red:'red'
},
//自定义指令,局部
directives:{
color: {
inserted: function(el,binding) {
console.log(el,binding);
el.style.color = binding.value;
}
}
}
});
global
<div id="app">
<!--red绑定到data里面的变量-->
<p v-color="red">我是自定义指令</p>
</div>
//自定义标签,全局
Vue.directive('color', {
inserted: function(el,binding) {
console.log(el,binding);
el.style.color = binding.value;
}
})
var vm = new Vue({
el: '#app',
data: {
red:'red'
}
});
Show results:
6. Vue components
Component introduction
- Component is one of the most powerful features of Vue.
- Components can extend HTML elements and encapsulate reusable code
- The component system allows us to build large-scale applications with independent and reusable small components, and the interface of almost any type of application can be abstracted into a component tree
- Components can be divided into global components and local components
Component Naming Rules
- Named with a dash, such as: my-component, vue recommends using this naming rule
- First letter capitalization naming rules, such as: MyComponent
props
- props is a custom property used by the parent component to pass data.
- The data of the parent component needs to be passed to the child component through props, and the child component needs to explicitly declare "prop" with the props option
local components
Definition syntax: new Vue({el:'#d1',components:{component name:{configuration options}}})
<div id="app">
<div>
<!--title是用来传值的自定义属性,在自定义组件的props中定义 -->
<button-counter title="测试"/>
</div>
</div>
var vm = new Vue({
el: '#app',
data: {
ts: new Date().getTime()
},
//局部自定义组件
components: {
//组件名: {配置项}
'button-counter': {
//用来传值的自定义属性
props:['title'],
//模板,模板中写的html代码,在其中可以使用{
{}},及指令等vue元素
template: '<button @click="doClick">{
{title}}:局部组件,点击计数器:{
{count}}</button>',
//注意:在自定义的组件中需要使用函数来定义data
data: function() {
return {
count: 0
}
},
//定义响应事件函数
methods: {
doClick: function() {
//注意此处this的作用返回是自定义组件,而不是上面声明
//的vue实例.
this.count++;
}
}
}
}
});
Note: Why do you have to use the function method to get what data in the custom component?
Each custom component declares data functionally, so that each instance maintains an independent copy of the returned object. Be careful when defining custom components.
global component
Modify the above local component to a global component.
Global component definition syntax: Vue.component (component name, configuration options)
<div id="app">
<div>
<button-counter title="测试"/>
</div>
</div>
//全局组件
Vue.component('button-counter', {
//用来传值的自定义属性
props:['title'],
//模板,模板中写的html代码,在其中可以使用{
{}},及指令等vue元素
template: '<button @click="doClick">{
{title}}: 全局组件,点击计数器:{
{count}}</button>',
//注意:在自定义的组件中需要使用函数来定义data
data: function() {
return {
count: 0
}
},
//定义响应事件函数
methods: {
doClick: function() {
//注意此处this的作用返回是自定义组件,而不是上面声明
//的vue实例.
this.count++;
}
}
});
var vm = new Vue({
el: '#app',
data: {
ts: new Date().getTime()
}
});
7. Custom events
Vue custom events are designed for communication between components. In Vue, the parent component passes data to the child component through props, and if you want to pass the data of the child component to the parent component, you can bind the custom event
- Parent Vue instance -> child Vue instance, passing data through prop
- Child Vue instance -> parent Vue instance, passing data through events
7.1 Child -> Parent
Triggering an event: $emit(eventName, parameters...)
Note: The event name must be named with a dash.
<div id="app">
<!--子组件到父组件-->
<div>
<button-counter v-on:click-test="clickTest"/>
</div>
</div>
var vm = new Vue({
el: '#app',
data: {
ts: new Date().getTime()
},
//对于自定义的button-counter组件, Vue实例为父组件
//在父组件中定义一个test方法,子组件调用该方法
methods: {
clickTest: function(msg) {
console.log("test: "+ msg);
}
},
//局部自定义组件
components: {
//组件名: {配置项}
'button-counter': {
//用来传值的自定义属性
props:['title'],
//模板,模板中写的html代码,在其中可以使用{
{}},及指令等vue元素
template: '<button @click="doClick">{
{title}}:局部组件,计数:{
{count}}</button>',
//注意:在自定义的组件中需要使用函数来定义data
data: function() {
return {
count: 0
}
},
//定义响应事件函数
methods: {
doClick: function() {
//注意此处this的作用返回是自定义组件,而不是上面声明的vue实例.
//注意事件名使用短横线命名方式
this.$emit("click-test","hello vue");
}
}
}
}
});
7.2 Parent -> Child
Note: When props define properties, they use camel case nomenclature, and when they are used in html, they need to be corresponding to dash nomenclature! !
<div id="app">
<!--子组件到父组件-->
<div>
<!-- 注意此处将定义props时的驼峰命名法,变为了短横线命名法 !!! -->
<button-counter title-desc="测试" />
</div>
</div>
var vm = new Vue({
el: '#app',
data: {
ts: new Date().getTime()
},
//对于自定义的button-counter组件, Vue实例为父组件
//在父组件中定义一个test方法,子组件调用该方法
methods: {
clickTest: function(msg) {
console.log("test: "+ msg);
}
},
//局部自定义组件
components: {
//组件名: {配置项}
'button-counter': {
//用来传值的自定义属性
//注意此处使用驼峰命名法 !!!
props:['titleDesc'],
//模板,模板中写的html代码,在其中可以使用{
{}},及指令等vue元素
template: '<button @click="doClick">{
{titleDesc}}:局部组件,计数:{
{count}}</button>',
//注意:在自定义的组件中需要使用函数来定义data
data: function() {
return {
count: 0
}
},
//定义响应事件函数
methods: {
doClick: function() {
//注意此处this的作用返回是自定义组件,而不是上面声明的vue实例.
//注意事件名使用短横线命名方式
this.count ++;
console.log(this.titleDesc);
}
}
}
}
});