Vue learning (a template syntax)

Vue (pronounced /vjuː/, similar to view ) is a progressive framework for building user interfaces

Use Vue to render helloworld on the page

insert image description here
The above is a simple vue use.

1. Difference expression

The above is an application of a difference expression, <div> { { value }} </div>but there will be a small bug when using the difference expression directly, and there is a defect of text flashing, because Vue will first display the difference expression on the page, and then When compiling, this sequence can see the changes between the two behaviors when we refresh quickly.
The solution is to add a directive to the div <div v-cloak> { { value }} </div>and then cssset the style [v-cloak] { display: none; }in it to hide it first, and then display it after vue is compiled.

2. Instructions

The essence is that custom attributes start with v- in vue;
v-textfilling plain text <div v-text=‘msg’> </div>
can directly fill the data into the page, and there will be no flickering problem of difference expressions. If there are HTML tags in the data, the html tags will be replaced and output.
Note : This is a one-way binding, the value on the data object changes, the interpolation will change; but when the interpolation changes, it will not affect the value of the data object

<div id="app">
    <!--  
		注意:在指令中不要写插值语法  直接写对应的变量名称 
        在 v-text 中 赋值的时候不要在写 插值语法
		一般属性中不加 {
    
    {
    
    }}  直接写 对应 的数据名 
	-->
    <p v-text="msg"></p>
    <p>
        <!-- Vue  中只有在标签的 内容中 才用插值语法 -->
        {
    
    {
    
    msg}}
    </p>
</div>

<script>
    new Vue({
    
    
        el: '#app',
        data: {
    
    
            msg: 'Hello Vue.js'
        }
    });

</script>

v-htmlThere are security issues in filling HTML fragments, the internal data of the website can be used, but not external.

<div id="app">
  <p v-html="html"></p> <!-- 输出:html标签在渲染的时候被解析 -->
    
    <p>{
    
    {
    
    message}}</p> <!-- 输出:<span>通过双括号绑定</span> -->
    
  <p v-text="text"></p> <!-- 输出:<span>html标签在渲染的时候被源码输出</span> -->
</div>
<script>
  let app = new Vue({
    
    
  el: "#app",
  data: {
    
    
    message: "<span>通过双括号绑定</span>",
    html: "<span>html标签在渲染的时候被解析</span>",
    text: "<span>html标签在渲染的时候被源码输出</span>",
  }
 });
</script>

v-preFill in the original data and skip the compilation process. For example, { { msg }}this . Do not compile with vue. Some static content does not need to be compiled. Adding this command can speed up rendering.

    <span v-pre>{
    
    {
    
     this will not be compiled }}</span>    
	<!--  显示的是{
    
    {
    
     this will not be compiled }}  -->
	<span v-pre>{
    
    {
    
    msg}}</span>  
     <!--   即使data里面定义了msg这里仍然是显示的{
    
    {
    
    msg}}  -->
<script>
    new Vue({
    
    
        el: '#app',
        data: {
    
    
            msg: 'Hello Vue.js'
        }
    });

</script>

v-onceAfter compiling and displaying once, the data response is no longer supported, which is generally when the information used for display does not need to be modified later.

  <!-- 即使data里面定义了msg 后期我们修改了 仍然显示的是第一次data里面存储的数据即 Hello Vue.js  -->
     <span v-once>{
    
    {
    
     msg}}</span>    
<script>
    new Vue({
    
    
        el: '#app',
        data: {
    
    
            msg: 'Hello Vue.js'
        }
    });
</script>

v-modelTwo-way data binding can be used for input, so that the value in the input and msg can be bound and interact with each other. Restricted for use <input>、<select>、<textarea>、componentsin .

<div id="app">
      <div>{
    
    {
    
    msg}}</div>
      <div>
          当输入框中内容改变的时候,  页面上的msg  会自动更新
        <input type="text" v-model='msg'>
      </div>
  </div>

ps: Two-way data binding is: when the data changes, the view also changes, and when the view changes, the data will also change synchronously.

3. Event binding

Handling various events is actually an instruction. The functions in Vue are written in methods, not in data.
Instruction Usage: v-on:xxShort Form: @xx
insert image description here
Click Event:

 <button v-on:click='num'></button>     <button @:click='num'></button>

Function call:
There is another question here, about the passing of function parameters.
There are two ways to write functions in vue:
direct binding function name: <button v-on:click='num'></button>
calling function: <button v-on:click='num("hi",$event)'></button>
the biggest difference is whether to pass parameters, in vue it is fixed $eventas the current event object, and the first parameter in the bound function in the first way is default is the current event object.

<body>
    <div id="app">
        <div>{
    
    {
    
    num}}</div>
        <div>
            <!-- 如果事件直接绑定函数名称,那么默认会传递事件对象作为事件函数的第一个参数 -->
            <button v-on:click='handle1'>点击1</button>
            <!-- 2、如果事件绑定函数调用,那么事件对象必须作为最后一个参数显示传递,
                 并且事件对象的名称必须是$event 
            -->
            <button v-on:click='handle2(123, 456, $event)'>点击2</button>
        </div>
    </div>
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript">
        var vm = new Vue({
    
    
            el: '#app',
            data: {
    
    
                num: 0
            },
            methods: {
    
    
                handle1: function(event) {
    
    
                    console.log(event.target.innerHTML)
                },
                handle2: function(p, p1, event) {
    
    
                    console.log(p, p1)
                    console.log(event.target.innerHTML)
                    this.num++;
                }
            }
        });
    </script>

Event modifiers:
Calling event.preventDefault()or event.stopPropagation()is a very common requirement. Some specific behaviors used to modify events.

.stop prevents bubbling <a v-on:click.stop='handle'>跳转</a>
. prevent prevents default behavior <a v-on:click.prevent='handle'>跳转</a>
. enter enter key <input v-on:keyup.enter='submit'>
. delete delete key input v-on:keyup.delete='submit'>
Modifiers can be written together in series, but the sequence and effect are different. For more event modifiers, refer to the official website documentation.

<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a>

<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- 修饰符可以串联   即阻止冒泡也阻止默认事件 -->
<a v-on:click.stop.prevent="doThat"></a>

<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>

Key modifiers:

<!-- 只有在 `keyCode`13 时调用 `vm.submit()` -->
<input v-on:keyup.13="submit">

<!-- -当点击enter 时调用 `vm.submit()` -->
<input v-on:keyup.enter="submit">

<!--当点击enter或者space时  时调用 `vm.alertMe()`   -->
<input type="text" v-on:keyup.enter.space="alertMe" >

常用的按键修饰符
.enter =>    enter键
.tab => tab键
.delete (捕获“删除”和“退格”按键) =>  删除键
.esc => 取消键
.space =>  空格键
.up =>.down =>.left =>.right =>

<script>
	var vm = new Vue({
    
    
        el:"#app",
        methods: {
    
    
              submit:function(){
    
    },
              alertMe:function(){
    
    },
        }
    })

</script>

Custom key modifier:
<input v-on:keyup.65='submit'>The keyCode of a obtained here is 65, but the subsequent function will be executed when the a key is pressed.
You can also define Vue.config.keyCode.aaa(custom) = 65 globally and input v-on:keyup.aaa='submit'>then implement custom modifiers.

<div id="app">
    预先定义了keycode 116(即F5)的别名为f5,因此在文字输入框中按下F5,会触发prompt方法
    <input type="text" v-on:keydown.f5="prompt()">
</div>

<script>
	
    Vue.config.keyCodes.f5 = 116;

    let app = new Vue({
    
    
        el: '#app',
        methods: {
    
    
            prompt: function() {
    
    
                alert('我是 F5!');
            }
        }
    });
</script>

4. Attribute binding

Processing each attribute is actually an instruction, which can be written in data.
Command usage: v-bind:xx Short form: :xx
<a v-bind:href='url'></a>

5. Style Binding

1. Class style processing method:
object syntax: <div v-bind:class='{ active(类名) : isActive(属性状态,必须在data中给参数,一般是true或false) }'></div>there can be multiple key-value pairs, separated by commas.

1、 v-bind 中支持绑定一个对象 
	如果绑定的是一个对象 则 键为 对应的类名  值 为对应data中的数据 
<!-- 
	HTML最终渲染为 <ul class="box textColor textSize"></ul>
	注意:
		textColor,textSize  对应的渲染到页面上的CSS类名	
		isColor,isSize  对应vue data中的数据  如果为true 则对应的类名 渲染到页面上 


		当 isColor 和 isSize 变化时,class列表将相应的更新,
		例如,将isSize改成falseclass列表将变为 <ul class="box textColor"></ul>
-->

<ul class="box" v-bind:class="{textColor:isColor, textSize:isSize}">
    <li>学习Vue</li>
    <li>学习Node</li>
    <li>学习React</li>
</ul>
  <div v-bind:style="{color:activeColor,fontSize:activeSize}">对象语法</div>

<sript>
var vm= new Vue({
    
    
    el:'.box',
    data:{
    
    
        isColor:true,
        isSize:true
    	activeColor:"red",
        activeSize:"25px",
    }
})
</sript>
<style>

    .box{
    
    
        border:1px dashed #f0f;
    }
    .textColor{
    
    
        color:#f00;
        background-color:#eef;
    }
    .textSize{
    
    
        font-size:30px;
        font-weight:bold;
    }
</style>

Array syntax: <div v-bind:class='[ activeClass, errorClass ]'></div>Here, each value in the array should be given its parameter in data, and the parameter value is the specific class name.

2、  v-bind 中支持绑定一个数组    数组中classA和 classB 对应为data中的数据

这里的classA  对用data 中的  classA
这里的classB  对用data 中的  classB
<ul class="box" :class="[classA, classB]">
    <li>学习Vue</li>
    <li>学习Node</li>
    <li>学习React</li>
</ul>
<script>
var vm= new Vue({
    
    
    el:'.box',
    data:{
    
    
        classA:‘textColor‘,
        classB:‘textSize‘
    }
})
</script>
<style>
    .box{
    
    
        border:1px dashed #f0f;
    }
    .textColor{
    
    
        color:#f00;
        background-color:#eef;
    }
    .textSize{
    
    
        font-size:30px;
        font-weight:bold;
    }
</style>

2. Syntax details related to style binding:
2.1 Object binding and array binding can be used in combination
[ activeClass, errorClass ,{ active(class name) : isActive } ]

2.2 The value of class binding can simplify the operation.
You can assign an array to an attribute in data, arrClass: [xxx,xxx]

, The object syntax can also be similarly operated, just assign it to an object.

2.3 How to deal with the default class?
The default class style will be preserved.

3. Style processing:
Object syntax: div v-bind:style=“{ color:activeColor,fontSize:fontSize}”> </div>Object attribute values ​​are set in data, or you can refer to the simplified method mentioned above to assign an object
Array syntax:div v-bind:style=“[ baseStyle,overrStyle ]”> </div>

<div v-bind:style="styleObject">绑定样式对象</div>'
 
<!-- CSS 属性名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用单引号括起来)    -->
 <div v-bind:style="{ color: activeColor, fontSize: fontSize,background:'red' }">内联样式</div>

<!--组语法可以将多个样式对象应用到同一个元素 -->
<div v-bind:style="[styleObj1, styleObj2]"></div>


<script>
	new Vue({
    
    
      el: '#app',
      data: {
    
    
        styleObject: {
    
    
          color: 'green',
          fontSize: '30px',
          background:'red'
        }
        activeColor: 'green',
   		fontSize: "30px"
      },
      styleObj1: {
    
    
             color: 'red'
       },
       styleObj2: {
    
    
            fontSize: '30px'
       }

</script>

6. Branch loop structure

Carry out conditional judgment and loop.
1. Branch structure:
v-if=xx
v-else-if=xx Only those that meet the conditions will be rendered in a group of judgments, and other unsatisfied conditions do not exist in the page structure
v-else=xx

v-show=xxIt will be rendered, but it will only be displayed if the conditions are met, otherwise it will be hidden.
The difference between v-show and v-if:

  • The essence of v-show is that the label display is set to none, and the control is hidden
    • v-show is only compiled once, and the latter is actually to control css, and v-if is constantly destroyed and created, so the performance of v-show is better.
  • v-if is to dynamically add or delete DOM elements to the DOM tree
    • The v-if switch has a partial compilation/unloading process, and the internal event listeners and subcomponents are properly destroyed and rebuilt during the switch process
<div id="app">
        <!--  判断是否加载,如果为真,就加载,否则不加载-->
        <span v-if="flag">
           如果flag为true则显示,false不显示!
        </span>
</div>

<script>
    var vm = new Vue({
    
    
        el:"#app",
        data:{
    
    
            flag:true
        }
    })
</script>

----------------------------------------------------------

    <div v-if="type === 'A'">
       A
    </div>
  <!-- v-else-if紧跟在v-if或v-else-if之后   表示v-if条件不成立时执行-->
    <div v-else-if="type === 'B'">
       B
    </div>
    <div v-else-if="type === 'C'">
       C
    </div>
  <!-- v-else紧跟在v-if或v-else-if之后-->
    <div v-else>
       Not A/B/C
    </div>

<script>
    new Vue({
    
    
      el: '#app',
      data: {
    
    
        type: 'C'
      }
    })
</script>

2. Loop structure:
v-for traverses the array
<li v-for=' item in list '>{ { item }}</li>
<li v-for='(item,index) in list'>{ { item }}+'-----'+{ {index}}</li>and provides indexes

<ul id="example-1">
   <!-- 循环结构-遍历数组  
	item 是我们自己定义的一个名字  代表数组里面的每一项  
	items对应的是 data中的数组-->
  <li v-for="item in items">
    {
    
    {
    
     item.message }}
  </li> 

</ul>
<script>
 new Vue({
    
    
  el: '#example-1',
  data: {
    
    
    items: [
      {
    
     message: 'Foo' },
      {
    
     message: 'Bar' }
    ]
   
  }
})
</script>

v-for traverses objects
<i v-for=' (value,key,index) in object '>{ { value(对象中属性的值)+'-----'+key(属性名)+'-----'+index(对应的索引0开始) }}</li>

   <!--  循环结构-遍历对象
		v 代表   对象的value
		k  代表对象的 键 
		i  代表索引	
	---> 
     <div v-if='v==13' v-for='(v,k,i) in obj'>{
    
    {
    
    v + '---' + k + '---' + i}}</div>

<script>
 new Vue({
    
    
  el: '#example-1',
  data: {
    
    
    items: [
      {
    
     message: 'Foo' },
      {
    
     message: 'Bar' }
    ]
    obj: {
    
    
        uname: 'zhangsan',
        age: 13,
        gender: 'female'
    }
  }
})
</script>

Notice:

  • It is not recommended to use v-ifbothv-for
  • v-ifWhen v-forused with , v-forhas v-ifhigher .
   <!--  循环结构-遍历对象
		v 代表   对象的value
		k  代表对象的 键 
		i  代表索引	
	---> 
     <div v-if='v==13' v-for='(v,k,i) in obj'>{
    
    {
    
    v + '---' + k + '---' + i}}</div>

<script>
 new Vue({
    
    
  el: '#example-1',
  data: {
    
    
    items: [
      {
    
     message: 'Foo' },
      {
    
     message: 'Bar' }
    ]
    obj: {
    
    
        uname: 'zhangsan',
        age: 13,
        gender: 'female'
    }
  }
})
</script>

It is better to have a key, which is used when recycling objects, and has the function:

  • key to uniquely identify each node
  • The role of the key is mainly to efficiently update the virtual DOM
<ul>
  <li v-for="item in items" :key="item.id">...</li>
</ul>

Generally, after we get the object, the object has a primary key, and the unique one can be used as the key. Here, the id attribute under the item object is used as the key.

Guess you like

Origin blog.csdn.net/xia_zai_ya/article/details/105841928