Vue study notes (2) [Built-in instructions of template syntax, custom instructions]

Vue study notes (2) [Built-in instructions and custom instructions of template syntax]

Review of


Vue study notes from past issues (1) [Template syntax, data binding, MVVM model]

built-in commands

v-show

Elements with v-showwill always be rendered and remain in the DOM. v-showJust simply toggle displaythe CSS property of the element.

Note that the element v-showis not supported <template>, nor is it supported v-else.

Use v-showconditional rendering

<div id="app">
    <!-- <div v-show="isShow">你好</div>
    <div v-if="isShow">你好</div>
    <div>
        <span v-show="grade>=90">优秀</span>
        <span v-show="grade>=90"></span>
        <span v-show="grade>=90"></span>
    </div> -->
</div>
<template id="root">
    <div v-show="isShow">你好</div>
    <div v-if="isShow">你好</div>
    <div>
        <span v-if="grade>=90">优秀</span>
        <span v-else-if="grade<90&&grade>=60">普通</span>
        <span v-else>不及格</span>
    </div>
</template>
<script>
    const app = Vue.createApp({
     
     
        template:'#root',
        data(){
     
     
            return {
     
     
                isShow:true,
                grade:90,
            }
        }
    })
    app.mount('#app')
</script>

Please add image description


v-if

Conditional judgment uses the instruction, which will be displayed only when v-ifthe expression of the instruction returns : because it is an instruction, it must be added to an element. If there are multiple elements, they can be wrapped on the element and used on it . The final rendering result will not contain elements. Directive to selectively render elements based on whether an expression is true or falsetrue
v-if<template>v-if<template>
v-if


### v-for Use the `v-for` instruction to loop through arrays and objects to obtain each value.

v-ifDirectives are used to conditionally render a block of content. This content will only truthybe rendered when the directive's expression returns a value.

Because v-ifis a directive, it must be added to an element. But what if you want to switch multiple elements?
At this time, you can treat an <template>element as an invisible wrapping element and use it on it v-if. The final rendering result will not contain <template>elements.

<div id="app"> 
</div>
<template id="root">
    <ul>
        <!-- v-for语法(item,index) in -->
        <li v-for="(item,index) in student">
            {
   
   {index}}-{
   
   {item}}
        </li>
    </ul>
    <button @click="add()">添加</button>
</template>
<script>
    const app = Vue.createApp({
     
     
        template:'#root',
        data(){
     
     
            return {
     
     
                student:["张三","李四","王麻子","奶茶"]
            }
        },
        methods:{
     
     
            add:function(){
     
     
                this.student.push('赵四');
            }
        }
    })
    app.mount('#app')
</script>

Please add image description


v-model

v-modelThe command is used to create two-way data binding on form control elements such as <input>, <select>, <textarea>, <checkbox>, <radio>etc., and automatically update the value of the bound element based on the value on the form.

Responsible for monitoring user input events and updating data, and processing some extreme scenarios

For button events, we can use v-onto listen for events and respond to user input.

<div id="app">
    <p>{
   
   { message }}</p>
    <button v-on:click="reverseMessage">反转字符串</button>
</div>
    
<script>
const app = {
     
     
  data() {
     
     
    return {
     
     
      message: 'Runoob!'
    }
  },
  methods: {
     
     
    reverseMessage() {
     
     
      this.message = this.message
        .split('')
        .reverse()
        .join('')
    }
  }
}
 
Vue.createApp(app).mount('#app')
</script>

v-on

v-onDirectives are used to listen to DOM events and run some JavaScript code when triggered.

v-onThe expression of the instruction can be a general JavaScript code, or it can be the name of a method or a method call statement.

When using v-ona command to bind an event, you need to v-onfollow the command with the event name.

v-on 缩写
<!-- 完整语法 -->
<a v-on:click="doSomething"></a>
<!-- 缩写 -->
<a @click="doSomething"></a>
<div id="app">
	<!-- 为元素绑定事件 -->
	<input type="button" value="v-on指令" v-on:click="doIt"/>
	<!-- 'v-on:'可以简写为 '@'-->
	<input type="button" value="事件绑定" @click="doIt"/><br>
	<input type="button" value="双击事件" @dblclick="doIt()"/>
	<h3 @click="changeWuqian">{
   
   { wuqian }}</h3>
</div>
<script type="text/javascript">
	let app = new Vue({
     
     
		el:'#app',
		data:{
     
     
			wuqian:"world很大"
		},
		methods:{
     
     
			doIt:function(){
     
     
				alert("嘿嘿");
			},
			changeWuqian:function(){
     
     
				//console.log(this.wuqian);
				this.wuqian+="你要忍一下~"
			}
		},
	})
</script>

v-bind

v-bindDirectives are mainly used to update HTML attributes responsively and dynamically bind one or more attributes or a component's prop to an expression.

v-bind abbreviation

<!-- 完整语法 -->
<a v-bind:href="url"></a>
<!-- 缩写 -->
<a :href="url"></a>
<div id="app">
    <p><a v-bind:href="url">Hello,你好</a></p>
</div>
    
<script>
const app = {
     
     
  data() {
     
     
    return {
     
     
      url: 'https://v3.cn.vuejs.org/'
    }
  }
}
 
Vue.createApp(app).mount('#app')
</script>

v-text

v-textDirective used to update the text content of an element. If you only need to update part of the text content, use interpolation to complete it.

<div id="text">
	
	<!-- v-text 向其所在的节点渲染 文本 节点 -->
	<div>现在正在使用{
   
   {name}}</div>
	<div v-text="name">haha</div>
	<!-- <h1>CSDN博客</h1> -->
	<div v-text="str"></div>
</div>
<script type="text/javascript">
	var text = new Vue({
     
     
		el:"#text",
		data:{
     
     
			name:'v-text指令',
			str:'<h1>CSDN博客</h1>',
		}
	})
</script>

v-html

v-htmlDirective is used to update the innerHTML element. Content is inserted as normal HTML and will not be compiled as a Vue template.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>v-html指令</title>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="text">
			<div>现在正在使用{
   
   {name}}</div>
			<!-- <h1>CSDN博客</h1> -->
			<div v-html="str"></div>
		</div>
		<script type="text/javascript">
			var text = new Vue({
     
     
				el:"#text",
				data:{
     
     
					name:'v-html指令',
					str:'<h1>CSDN博客</h1>',
				}
			})
		</script>
	</body>
</html>


v-once

v-onceThe directive does not require an expression. v-onceThe directive only renders the element and directive once. In subsequent renderings, elements, components and all child nodes that use this directive will be treated as static content and skipped, which can be used to optimize update performance.

<div id="root">
	<!-- v-once 所在节点在初次动态渲染后,就视为静态内容了
		 以后数据的改变不会引起 v-once 所在结构的更新 -->
	<h3 v-once>初始化的n值:{
   
   {n}}</h3>
	{
   
   {n}}
	<button type="button" @click="n++">点击+1</button>
</div>
<script type="text/javascript">
	var once = new Vue({
     
     
		el:"#root",
		data:{
     
     
			n:1,
		}
	})
</script>

in-for

v-preThe directive does not require an expression
to skip compilation of this element and its children. Can be used to display the original Mustache tag. Skipping a large number of nodes without instructions will speed up compilation.

<span v-pre>{
   
   { this will not be compiled }}</span>

Custom instructions

In addition to the default set of core directives (v-model and v-show), Vue also allows the registration of custom directives.

Next we register a global directive v-focus. The function of this directive is to focus the element when the page is loaded:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自定义指令</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <!-- v-for -->
    <div id="app">  
    </div>
    <template id="root">
        <input type='text' v-focus>
    </template>
    <script>
        const app = Vue.createApp({
     
     
            template:'#root',
            directives:{
     
     
                focus:{
     
     
                    mounted(el){
     
     
                        el.focus()
                    }
                }
            },
        })
        // 全局注册
        // app.directive('focus',{
     
     
        //     mounted(el){
     
     
        //         el.focus()
        //     }
        // })

        app.mount('#app')
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/yuyunbai0917/article/details/123572585