vue tag review

vue tag review

Reference article

https://mp.weixin.qq.com/s/jS6Qx2PfZDvhQ7r870RoFA

Description:

This post is a reference. I have tested each of the above examples. It will be convenient to review and check early in the future, as a vue entry tool document

Vue is a progressive framework for building user interfaces . Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up.

Vue's core library only focuses on the view layer, which is not only easy to use, but also easy to integrate with third-party libraries or existing projects. On the other hand, when combined with modern tool chains and various supporting libraries, Vue is also fully capable of providing drivers for complex single-page applications.

So how to introduce Vue on the page? How to use Vue for development? Let's get to know Vue together next. First create an html page and introduce Vue.js:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

You can also download the vue.js file directly to the local, and then import it.

Next look at a piece of sample code:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <div id="app">
        <!-- {
   
   {}} 可以取出data定义的数据 -->
        <p>{
   
   {msg}}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:'#app',
            data:{
                msg:'Hello Vue!'
            }
        });
    </script>
</body>
</html>

Create a Vue instance, where el specifies the DOM that needs to be controlled, here specified as #app, then the div scope of the app is the control scope of Vue; secondly is data, which can define the data used in the scope in the form of key value Yes, of course, the content that can be defined in the Vue instance is much more than that, but let's take a look at the effect of this code first:

image

Vue instructions

Vue provides a very convenient way to control and manipulate the DOM, that is, Vue instructions. Vue provides a variety of instructions. Let's first understand the more commonly used instructions.

v-cloak

Just now we use { {}}symbols to remove the data defined in the data, this symbol is called 插值表达式. However, this data out there is a drawback, when the network fluctuations, interpolation will be displayed on the page, rather than show the true expression of data:

image

This will obviously cause a bad experience for users. For this reason, we can use the v-cloak command to solve this problem:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<style>
    [v-cloak] {
        display: none;
    }
</style>
<body>
    <div id="app">
        <p v-cloak>{
   
   {msg}}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:'#app',
            data:{
                msg:"Hello Vue!"
            }
        });
    </script>
</body>
</html>

If this is done, the DOM element modified by v-cloak will be hidden before the msg data is retrieved, thus solving the flickering problem of the interpolation expression.

v-text & v-html

These two commands are used to display data:

<p v-text="msg"></p>
<p v-html="msg"></p>

They are no different in display effect:

image

But there are still some differences between these two instructions. First of all, v-text and v-html commands do not have flicker problems. Secondly, they directly overwrite the data on the DOM, so the original data of the DOM will disappear; but the v-html command can also parse the tags in the data. And v-text cannot:

<div>
  <p v-text="msg"></p>
  <p v-html="msg"></p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el:'#app',
    data:{
      msg:"<h1>Hello Vue!</h1>"
    }
  });
</script>

display effect:

image

v-bind

Sometimes the v-text and v-html commands cannot meet our needs, such as providing a button prompt message. At this time, we can use the v-bind command:

<div id="app">
  <input type="button" v-bind:title="msg" value="按钮"/>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el:'#app',
    data:{
      msg:"这是一个按钮"
    }
  });
</script>

The effect is as follows:

image

The v-bind instruction is used to bind DOM attributes, that is to say, as long as it is a DOM attribute, it can be bound directly, such as the value attribute of the input box:

<input type="button" v-bind:title="msg" v-bind:value="msg"/>

The effect is as follows:

image

v-bind can also bind styles:

<style>
  .red {
    color: red;
  }
  .thin {
    font-weight: 200;
  }
</style>
<body>
  <div id="app">
    <h1 v-text="msg" v-bind:class="['red','thin']"></h1>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    var app = new Vue({
      el: '#app',
      data: {
        msg: 'Hello Vue!'
      },
    });
  </script>

There are several ways to bind styles through v-bind. This is one of them. Use array binding. Note that the style names in the array must be enclosed in quotation marks. We can also bind through objects:

<div id="app">
  <h1 v-text="msg" v-bind:class="{red:true,thin:true}"></h1>
</div>

But behind the style name in this manner must keep pace :trueor :falseso we can set a flag dynamically by defining the data:

<div id="app">
  <h1 v-text="msg" v-bind:class="{red:flag,thin:flag}"></h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      msg: 'Hello Vue!',
      flag: true
    },
  });
</script>

At this time, the flag can control whether the style is displayed.

The v-bind instruction can be abbreviated as :, for example:

<input type="button" :title="msg" :value="msg"/>

v-for

This instruction is used for loop operation:

<div id="app">
  <p v-for="item in array">
    {
   
   {item}}
  </p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      array: [1, 2, 3, 4, 5]
    },
  });
</script>

The syntax of the v-for instruction is item(为数组中的每一项取一个名字) in list(待遍历的数组名), then item is each element in the array, and the effect is as follows:

image

Sometimes we need to get the index value of the current element, we can write like this:

<p v-for="(item,index) in array">
  {
   
   {index}} ---- {
   
   {item}}
</p>

For more complex arrays, v-for can of course also be easily traversed:

<div id="app">
  <p v-for="(user,index) in array">
    索引值:{
   
   {index}}--id:{
   
   {user.id}}--name:{
   
   {user.name}}--age:{
   
   {user.age}}
  </p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      array:[
        {id:1,name:'张三',age:20},
        {id:2,name:'李四',age:21},
        {id:3,name:'王五',age:22},
      ]
    },
  });
</script>

The effect is as follows:

image

The v-for instruction can also traverse objects:

<div id="app">
  <p v-for="(value,key,index) in user">
    索引:{
   
   {index}}---{
   
   {key}}:{
   
   {value}}
  </p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      user: { id: 1, name: '张三', age: 20 }
    }
  });
</script>

The effect is as follows:

image

One thing to pay attention to when using the v-for instruction, in versions after Vue 2.2.0, when using v-for in a component, you must carry the key attribute, and it is necessary to explain its function.

When the Vue is being updated with a v-for already rendered list elements, using the default 就地复用policy, if the order of the data item is changed, Vue will simply reuse each element here, rather than moving the DOM element to match order;

In order to give Vue a hint so that Vue can track the identity of each node, thereby reusing and reordering existing elements, we need to provide a unique attribute key for each item:

<div id="app">
  <div>
    <label>id:</label>
    <input type="text" v-model="id">
    <label>name:</label>
    <input type="text" v-model="name">
    <input type="button" value="添加" @click="add">
  </div>
  <p v-for="user in array">
    <input type="checkbox">
    {
   
   {user.id}}--{
   
   {user.name}}
  </p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      id: '',
      name: '',
      array: [
        { id: 1, name: '张三' },
        { id: 2, name: '李四' },
        { id: 3, name: '王五' }
      ]
    },
    methods: {
      add() {
        this.array.unshift({ id: this.id, name: this.name });
      }
    },
  });
</script>

This page is used to add data, and the effect is as follows:

image

When you fill in the data above and click Add, the data will be displayed in the list below, but this program has some problems:

image

When data No. 3 is selected and data No. 4 is added, the result is as follows:

image

The selected data is modified to number 2. This is the consequence of not specifying the key. We only need to set a unique attribute for the key when traversing:

<p v-for="user in array" :key="user.id">
  <input type="checkbox">
  {
   
   {user.id}}--{
   
   {user.name}}
</p>

Note that the key can only be set to string or number type values.

v-if & v-show

These two instructions are used to control the display and hiding of the DOM:

<div id="app">
  <p v-if="flag">v-if</p>
  <p v-show="flag">v-show</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      flag: true
    }
  });
</script>

The effect is as follows:

image

At first glance, there seems to be no difference between the two, but look at the source code:

image

When we set the flag to false, the v-if instruction will directly delete the DOM element, while the v-show instruction just sets the display attribute to none, which hides the DOM.

v-on

This instruction is used for event binding, such as:

<div id="app">
  <input type="button" value="按钮" v-on:click="show"/>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el:'#app',
    data:{
    },
    methods: {
      show(){
        alert("点击了按钮");
      }
    }
  });
</script>

You can bind events through v-on, and specify the event to be bound after v-on. Click is the click event, and its value is the name of the function that needs to be triggered. The function must be written in the methods attribute of the Vue instance. If you want to bind other events, such as the mouse removal event:

<input type="button" value="按钮" v-on:mouseover="show"/>

v-click can also be abbreviated as @:

<input type="button" value="按钮" @click="show"/>

Event modifier

Vue provides some event modifiers to deal with some common problems encountered in the event, the types are as follows:

  • stop: stop the event from bubbling
  • prevent: Organization default behavior
  • capture: Use event capture mode when adding event listeners
  • self: The callback is triggered only when the event element is triggered on the element itself (such as not a child element)
  • once: the event is triggered only once

stop

<div id="app" style="width: 150px;height: 150px;background-color: red;" @click="divClick">
  <input type="button" value="按钮" @click="btnClick"/>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {

    },
    methods: {
      divClick(){
        alert("点击了DIV");
      },
      btnClick(){
        alert("点击了按钮");
      }
    },
  });
</script>

In this page, there is a button in the div:

image

Due to the event bubbling mechanism, when the button is clicked, the button's event will be triggered first, and the div's click event will also be triggered. However, in some scenarios, we don't want to trigger the parent tag's event when the button is clicked. For this, we can use stop to prevent the bubbling of events:

<input type="button" value="按钮" @click.stop="btnClick"/>

prevent

<div id="app">
  <a href="http://www.baidu.com" @click="aClick">百度一下</a>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {

    },
    methods: {
      aClick(){
        alert("点击了超链接");
      }
    },
  });
</script>

There is a hyperlink on this page. Clicking on it will jump to the Baidu homepage. However, the hyperlink is bound to a click event, but because of the jump nature of the hyperlink, the click event cannot be triggered. For this reason, you can use prevent To prevent the default behavior of hyperlinks:

<a href="http://www.baidu.com" @click.prevent="aClick">百度一下</a>

capture

Still for the second example:

image

Through capture, the event listener can be modified to capture mode. The default is the bubbling mechanism. If capture is used, events can be passed from the outside to the inside:

<div id="app" style="width: 150px;height: 150px;background-color: red;" @click.capture="divClick">
  <input type="button" value="按钮" @click="btnClick" />
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {

    },
    methods: {
      divClick() {
        alert("点击了DIV");
      },
      btnClick() {
        alert("点击了按钮");
      }
    },
  });
</script>

Clicking the button at this time will pop up the DIV first, and then pop up the button.

self

<div id="app" style="width: 150px;height: 150px;background-color: red;" @click.self="divClick">
  <input type="button" value="按钮" @click="btnClick" />
</div>

self means that only events triggered by itself will execute the callback method. For example, on this page, if the button is clicked, the click event of the button will be triggered. Due to the bubbling mechanism of the event, the outer div will also trigger the click event, but because of the external The layer div uses self, which is not an event triggered by itself, so the click event of the div will not be triggered.

once

This modifier can ensure that the event is triggered only once:

<div id="app">
  <a href="http://www.baidu.com" @click.prevent.once="aClick">百度一下</a>
</div>

Event modifiers can be used in combination. The hyperlink in the page is set to prevent the default behavior once, the first click will trigger the aClick click event, and the next click will jump to the Baidu homepage.

Two-way data binding

Through the previous study, we learned that v-text, v-html, and v-bind can display the data in data to the DOM, but this is only a one-way data binding process, that is: the data in data is bound Set to the DOM, and the change of the data in the DOM does not affect the data in the data, for example:

<div id="app">
  <input type="text" :value="msg"/>
  <input type="text" :value="msg"/>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      msg: 'Hello Vue!'
    },
  });
</script>

The effect is as follows:

image

Both input boxes are bound to msg data, but the modification of the contents of these two boxes does not affect each other. In order to achieve two-way binding of data, you can use the v-model command:

<div id="app">
  <input type="text" v-model="msg"/>
  <input type="text" v-model="msg"/>
</div>

The effect is as follows:

image

The values ​​of these two input boxes will be updated synchronously, because the modification of the content of the input box will affect the value of msg in data, which is the two-way binding of data; but it should be noted that the v-model instruction can only be used for form elements.

filter

There is a label showing the date:

<div id="app">
  <label>{
   
   {new Date()}}</label>
</div>

The effect is as follows:

image

This is obviously not a friendly date display. For this, we can use the filter provided by Vue to format the date:

<div id="app">
  <label>{
   
   {new Date() | dateFormat}}</label>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>
  // 定义全局的过滤器
  Vue.filter('dateFormat', function (dateStr) {
    // 根据时间字符串构建Date对象
    var dt = new Date(dateStr);
    // 获取年、月、日
    var year = dt.getFullYear();
    var month = dt.getMonth() + 1;
    var day = dt.getDate();
    // 格式化日期
    return `${year}-${month}-${day}`;
  });

  var app = new Vue({
    el: '#app',
    data: {
    }
  });
</script>

Define a global filter through Vue.filter() and provide two parameters. The first parameter is the name of the filter, and the second parameter is the logic code that the filter needs to process. The date is processed correctly in the function and returned. can; then note during use, the filter using the pipeline at |the data connection to be processed, followed by the filter pipe character name, character data at this time will be in front of the duct as a function of processing filter parameters.

When calling the filter for processing, you can also continue to pass in other parameters, such as:

<label>{
   
   {new Date() | dateFormat('yyyy-mm-dd')}}</label>
<script>
  Vue.filter('dateFormat', function (dateStr,pattern) {
    ......
  });
</script>

This filter defined by Vue.filter() is a global filter, which works on all Vue instances. Of course, we can also define a private filter that only works on the current Vue instance:

<script>
  var app = new Vue({
    el: '#app',
    data: {
    },
    filters: {
      // 定义私有过滤器
      dateFormat: function (dateStr) {
        // 根据时间字符串构建Date对象
        var dt = new Date(dateStr);
        // 获取年、月、日
        var year = dt.getFullYear();
        var month = dt.getMonth() + 1;
        var day = dt.getDate();
        // 格式化日期
        return `${year}-${month}-${day}`;
      }
    }
  });
</script>

If there are both a private filter and a global filter, the private filter is used by default (the principle of proximity).

Key modifier

General websites have the function of confirming and filling in the information by pressing Enter. Let's simulate it:

<div id="app">
  <input type="text" v-model="msg" @keyup.enter="add">
  <p>{
   
   {result}}</p>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>
  var app = new Vue({
    el: '#app',
    data: {
      msg: '',
      result:''
    },
    methods: {
      add(){
        this.result = this.msg;
      }
    },
  });
</script>

The effect is as follows:

image

When you enter content in the input box and press Enter, the next page will display the input content. This is because we set the keyboard click event of the input box, and the key modifier can accurately control which key is pressed on the keyboard. Trigger the callback function, such as here .enter, it represents the enter key. Other key modifiers are as follows:

  • .tab
  • .delete
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

These are some commonly used modifiers defined by Vue for the convenience of development. For other keys, we can only use the corresponding keyword codes to set:

<input type="text" v-model="msg" @keyup.113="add">

113 corresponds to the button F2. At this time, clicking F2 will trigger the callback function. To make it easier to distinguish, we can also set aliases for these key codes:

<script>
  // 定义按键修饰符
  Vue.config.keyCodes = {
    "F1": 113,
  };
</script>

At this time, use the alias:

<input type="text" v-model="msg" @keyup.f2="add">

Custom instruction

There is an input box:

<div id="app">
  <input type="text" id="it">
</div>

If you want to automatically get the focus of the input box after refreshing the page, how to achieve it? In fact, very simple, you can call the input box focusfunction:

<div id="app">
  <input type="text" id="it">
</div>

<script>
  document.getElementById('it').focus();
</script>

But Vue does not recommend that we directly manipulate the DOM, so we can convert it into a custom instruction:

<div id="app">
  <input type="text" v-focus>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  // 自定义指令
  Vue.directive('focus', {
    // 当指令绑定到指定元素上时调用此函数,只执行一次
    bind(el) { // el即为绑定该指令的元素

    },
    // 当元素插入到DOM时调用此函数,只执行一次
    inserted(el) {
      el.focus();
    },
    // 当元素更新时调用此函数,执行多次
    updated(el) {

    }
  });
</script>

It should be noted, by the custom instruction Vue.directiveset, requires two parameters, the first parameter is the name of the command, the second parameter is an object, function definition requires three cycles in the effective date of the subject, the periodic function the parameters can be acquired into the binding elements of the instruction, and then calls the focusget focus can.

When using this command also needs to pay attention, must precede a custom command name v-prefix.

So how do custom instructions implement value passing:

<div id="app">
  <input type="text" v-color="'red'">
</div>

Customize a v-color command, and set the font color of the input box according to the passed parameter value, the realization is as follows:

<script>
  // 自定义指令
  Vue.directive('color', {
    // 当指令绑定到指定元素上时调用此函数,只执行一次
    bind(el,binding) { // el即为绑定该指令的元素
      el.style.color = binding.value;
    },
    // 当元素插入到DOM时调用此函数,只执行一次
    inserted(el) {
    },
    // 当元素更新时调用此函数,执行多次
    updated(el) {

    }
  });
</script>

Through the second parameter of the periodic function binding, we can get a lot of information, among which the value attribute is the value set by the instruction, and the value can be set in the style.

What we just defined are global directives. We can also define private directives that only belong to a certain Vue instance itself. Similar to filters, you only need to define them in the Vue instance:

<script>
  var app = new Vue({
    el: '#app',
    data: {
    },
    directives: {
      // 自定义私有指令
      'color': {
        // 当指令绑定到指定元素上时调用此函数,只执行一次
        bind(el, binding) { // el即为绑定该指令的元素
          el.style.color = binding.value;
        },
        // 当元素插入到DOM时调用此函数,只执行一次
        inserted(el) {
        },
        // 当元素更新时调用此函数,执行多次
        updated(el) {
        }
      }
    }
  });
</script>

Vue also provides an easier way to customize instructions:

<script>
  Vue.directive('Vue', function (el,binding) {
    el.style.color = binding.value;
  });
</script>

But this method will only take effect in bind and updated periodic functions. It is equivalent to pasting a copy of the code in the function in both bind and updated functions.

},
// This function is called when the element is updated, and
updated(el) is executed multiple times {

}

});


通过周期函数的第二个参数 `binding` ,我们能够获取到很多信息,其中value属性即为指令设置的值,将该值设置到样式中即可。

刚才定义的是全局指令,我们也可以定义只属于某个Vue实例本身的私有指令,与过滤器类似,只需在Vue实例中定义即可:


Vue还提供了一种更简便的方式来自定义指令:


但这种方式只会生效于bind和updated周期函数,它等同于将函数中的代码在bind和updated函数中均粘贴一份。



Guess you like

Origin blog.csdn.net/shaoming314/article/details/115256262