Home > Web Front-end > JS Tutorial > Detailed introduction to Vue data binding

Detailed introduction to Vue data binding

亚连
Release: 2018-06-13 13:51:46
Original
1735 people have browsed it

This article mainly introduces the use of exploring Vue high-level components. Now I share it with you and give you a reference.

1. What is two-way binding?

The core function of the Vue framework is two-way data binding. Bidirectional means: HTML tag data is bound to the Vue object, and data in the opposite direction is also bound. In layman's terms, changes in the Vue object will directly affect changes in HTML tags, and changes in tags will in turn affect changes in the properties of the Vue object.

Since then, the previous Dom development method has been completely changed. The previous Dom-driven development method, especially the jQuery-based development era, was to trigger js events after the DOM changes, and then pass the event in the event. The js code obtains the tag changes, interacts with the background, and then updates the HTML tags based on the results returned by the background, which is extremely cumbersome. With Vue's two-way binding, developers only need to care about changes in json data. Vue automatically maps to HTML, and changes in HTML will also be mapped back to js objects. The development method directly changes to the front-end data-based The era of driver-driven development has far abandoned the era dominated by Dom development.

""

2. Vue binding text

The most common form of data binding is to use "Mustache " Text interpolation of syntax (double braces), such as template engine: handlebars is used {{}}.

The data attribute in the created Vue object is used for binding Data to HTML. Refer to the following code:

<span>Message: {{ msg }}</span>
<script>
 var app = new Vue({     // 创建Vue对象。Vue的核心对象。
  el: &#39;#app&#39;,        // el属性:把当前Vue对象挂载到 p标签上,#app是id选择器
  data: {          // data: 是Vue对象中绑定的数据
   msg: &#39;Hello Vue!&#39;  // message 自定义的数据
  }
 });
</script>
Copy after login

3. Use JavaScript expressions in binding data

For all data binding, Vue.js Full JavaScript expression support is provided.

<span>Message: {{ msg + &#39; - &#39; + name }}</span>
<script>
 var app = new Vue({     // 创建Vue对象。Vue的核心对象。
  el: &#39;#app&#39;,        // el属性:把当前Vue对象挂载到 p标签上,#app是id选择器
  data: {          // data: 是Vue对象中绑定的数据
   msg: &#39;Hi&#39;,       // message 自定义的数据
   name: &#39;flydragon&#39;    // name自定义的属性,vue可以多个自定义属性,属性类型也可是复杂类型
  }
 });
</script>
Copy after login

Result:

Hi - flydragon
Copy after login

Of course Vue can also support any calculation, function processing, etc. in the expression. See the comprehensive point example below.

<!DOCTYPE html> 
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Vue入门之数据绑定-表达式运算</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <p id="app">
  {{ msg + &#39; - &#39; + name }}
  <p>
   {{ isOk ? &#39;123&#39; : &#39;456&#39; }}
  </p>
  <p>我的年龄是: {{ age *2 }}</p>
 </p>

 <script>
 var app = new Vue({     // 创建Vue对象。Vue的核心对象。
  el: &#39;#app&#39;,        // el属性:把当前Vue对象挂载到 p标签上,#app是id选择器
  data: {          // data: 是Vue对象中绑定的数据
   msg: &#39;Hi&#39;,       // message 自定义的数据
   name: &#39;flydragon&#39;,
   isOk: true,
   age: 18
  }
 });
 </script>
</body>
</html>
Copy after login

4. Vue attribute binding

You cannot directly use the {{ expression }} syntax for binding in Vue Instead of defining the html tag, use its unique v-bind instruction (which is a way of writing, follow the format first, and you can learn about the specific instructions later).

Binding syntax structure:

<标签 v-bind:属性名="要绑定的Vue对象的data里的属性名"></标签>
例如:
<span v-bind:id="menuId">{{ menuName }}</span>
Copy after login

Refer to the following code example:

<!DOCTYPE html> 
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Vue入门之数据绑定--属性绑定</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <p id="app">
  <p v-bind:id="MenuContaineId">
   <a href="#" v-bind:class="MenuClass">首页</a>
   <a href="#" v-bind:class="MenuClass">产品</a>
   <a href="#" v-bind:class="MenuClass">服务</a>
   <a href="#" v-bind:class="MenuClass">关于</a>
  </p>
 </p>

 <script>
  var app = new Vue({     
   el: &#39;#app&#39;,        
   data: {          // data: 是Vue对象中绑定的数据
    MenuClass: &#39;top-menu&#39;,
    MenuContaineId: &#39;sitemenu&#39;
   }
  });
 </script>
</body>
</html>
Copy after login

5. Abbreviation of attribute binding

Since v-bind is used very frequently, Vue provides a simple writing method. You can remove v-bind and use : directly.

例如:
<p :id="MenuContaineId">
等价于
<p v-bind:id="MenuContaineId">
Copy after login

6. Output pure HTML

Because Vue encodes the output bound content in advance, it is guaranteed to be bound to the page It will not be attacked by xss when displayed. But in some scenarios, we ensure that the background data is safe, then we have to display native HTML tags in the web page. Vue provides the v-html directive.

<p id="app">
 <p v-bind:id="MenuContaineId" v-html="MenuBody">
 </p>
</p>
<script>
 var app = new Vue({     
  el: &#39;#app&#39;,        
  data: {          // data: 是Vue对象中绑定的数据
   MenuContaineId: &#39;menu&#39;,
   MenuBody: &#39;<p>这里是菜单的内容</p>&#39;
  }
 });
</script>
Copy after login

Result:

<p id="app">
 <p id="menu">
  <p>这里是菜单的内容</p>
 </p>
</p>
Copy after login

7. Style binding

For ordinary attribute binding, you can only use the binding mentioned above attribute method. Vue specifically strengthens the binding of class and style attributes. There can be complex object bindings, array binding styles and classes.

7.1. Binding style objects

Often we need to switch styles, such as showing and hiding p, active tags, etc. The object binding style method provided by Vue makes it easy to do these things.

Code:

<p v-bind:class="{ active: isActive }"></p>
Copy after login

Explanation: When isActive is true, p will have an active style class. If isActive is false, then p will remove the active style class.

<!DOCTYPE html> 
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Vue入门之绑定样式类</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
 <style>
 .active {
  background-color: #ccc;
 }
 </style>
</head>
<body>
 <p id="app">
  <p v-bind:id="MenuContaineId" v-bind:class="{ active: isActive }">
   绑定颜色类
  </p>
 </p>
 <script>
  var app = new Vue({     
   el: &#39;#app&#39;,        
   data: {          // data: 是Vue对象中绑定的数据
    MenuContaineId: &#39;menu&#39;,
    isActive: true
   }
  });
 </script>
</body>
</html>
Copy after login

7.2. Mixing ordinary HTML tag style classes and bound style objects

The v-bind:class directive can coexist with ordinary class attributes.

<p id="app">
 <p class="static"
   v-bind:class="{ active: isActive, &#39;text-danger&#39;: hasError }">
 </p>
</p>
<script>
 var app = new Vue({     
  el: &#39;#app&#39;,        
  data: {          // data: 是Vue对象中绑定的数据
   isActive: true,
   hasError: false
  }
 });
</script>
Copy after login

Result:

<p id="app">
 <p class="static active">
 </p> 
</p>
Copy after login

7.3. Bind the style object in data

Write the object directly within the double quotes in the html attribute, or It’s very frustrating, and there are no smart prompts, so it’s easy to make mistakes. Vue allows us to directly point the bound class string to an object of data, which is very convenient. It can not only have smart prompts, but also make complicated editing, without worrying about the annoying "". .

<p id="app">
 <p class="static"
   v-bind:class="classObject">
 </p>
</p>
<script>
 var app = new Vue({     
  el: &#39;#app&#39;,        
  data: {
   classObject: {
    active: true,
    &#39;text-danger&#39;: false
   }
  }
 });
</script>
Copy after login

Result:

<p id="app">
 <p class="static active">
 </p>
</p>
Copy after login

7.4. Binding style array

In fact, the binding array is the continuation of the binding style object, see the official website Sample code.

<p v-bind:class="[activeClass, errorClass]">

data: {
 activeClass: &#39;active&#39;,
 errorClass: &#39;text-danger&#39;
}
Copy after login

Of course there are many other interesting supports, so I won’t go into details.

For example:

<p v-bind:class="[isActive ? activeClass : &#39;&#39;, errorClass]">
<p v-bind:class="[{ active: isActive }, errorClass]">
Copy after login

7.5. Inline style binding

The binding of inline style is very similar to the operation of style class. The object syntax of v-bind:style is very intuitive - it looks very like CSS, but it is actually a JavaScript object. CSS property names can be named in camelCase or kebab-case.

Look at an example:

<!DOCTYPE html> 
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Vue入门之htmlraw</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <p id="app">
  <p v-bind:style="{fontSize: size + &#39;px&#39;, backgroundColor: bgcolor, width: width}">
   vue 入门系列教程
  </p>
 </p>
 <script>
  var app = new Vue({     
   el: &#39;#app&#39;,        
   data: {          
    size: 19,
    width: 200,
    bgcolor: &#39;red&#39;
   }
  });
 </script>
</body>
</html>
Copy after login

Automatically add prefix

When v-bind:style uses CSS properties that require a specific prefix, such as transform, Vue.js will automatically detect test and add the appropriate prefix.

8. Computed properties

在做数据的绑定的时候,数据要进行处理之后才能展示到html页面上,虽然vue提供了非常好的表达式绑定的方法,但是只能应对低强度的需求。比如: 把一个日期按照规定格式进行输出,可能就需要我们对日期对象做一些格式化的出来,表达式可能就捉襟见肘了。

Vue对象提供的computed属性,可以让我们开发者在里面可以放置一些方法,协助我们绑定数据操作,这些方法可以跟data中的属性一样用,注意这些方法用的时候不要加()。 例子来了:

<!DOCTYPE html> 
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Vue入门之htmlraw</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <p id="app">
  <table>
   <tr>
    <!-- computed里面的函数可以直接当成data里面的属性用,非常方便,注意没有括号!!!-->
    <td>生日</td><td>{{ getBirthday }}</td>
   </tr>
   <tr>
    <td>年龄</td><td>{{ age }}</td>
   </tr>   
   <tr>
    <td>地址</td><td>{{ address }}</td>
   </tr>
  </table>
 </p>
 <script>
  var app = new Vue({     
   el: &#39;#app&#39;,        
   data: {          
    birthday: 914228510514,   // 这是一个日期对象的值:1998年11月1日
    age: 19,
    address: &#39;北京昌平区龙泽飞龙&#39;
   },
   computed: {
    // 把日期换成 常见规格格式的字符串。
    getBirthday: function () {
     var m = new Date(this.birthday);
     return m.getFullYear() + &#39;年&#39; + m.getMonth() +&#39;月&#39;+ m.getDay()+&#39;日&#39;;
    }
   }
  });
 </script>
</body>
</html>
Copy after login

9. 绑定的数据过滤器

过滤器本质就是数据在呈现之前先进行过滤和筛选。官网上写的不错,我就不再赘述,下面是官网的描述。

Vue.js 允许你自定义过滤器,被用作一些常见的文本格式化。过滤器应该被添加在 mustache 插值的尾部,由“管道符”指示:

{{ message | capitalize }}
<!-- in mustaches -->
{{ message | capitalize }}
<!-- in v-bind -->
<p v-bind:id="rawId | formatId"></p>
Copy after login

Vue 2.x 中,过滤器只能在 mustache 绑定和 v-bind 表达式(从 2.1.0 开始支持)中使用,因为过滤器设计目的就是用于文本转换。为了在其他指令中实现更复杂的数据变换,你应该使用计算属性。

过滤器函数总接受表达式的值作为第一个参数。

new Vue({
 // ...
 filters: {
  capitalize: function (value) {
   if (!value) return &#39;&#39;
   value = value.toString()
   return value.charAt(0).toUpperCase() + value.slice(1)
  }
 }
})
Copy after login

过滤器可以串联:

{{ message | filterA | filterB }}
Copy after login

过滤器是 JavaScript 函数,因此可以接受参数:

{{ message | filterA(&#39;arg1&#39;, arg2) }}
Copy after login

这里,字符串 'arg1' 将传给过滤器作为第二个参数, arg2 表达式的值将被求值然后传给过滤器作为第三个参数。

10. 核心:自动响应对象的变化到HTML标签

上面的例子都是 数据对象是写死在创建的Vue对像上,那如果数据(data)发生改变时会怎样呢? 让我们用chrome把上面例子的页面打开,并打开发者工具控制台,输入:app.age = 20会有什么情况发生呢?

""

在页面中添加一个按钮,动态的增加年龄:

<!DOCTYPE html> 
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Vue入门之htmlraw</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <p id="app">
  <table>
   <tr>
    <!-- computed里面的函数可以直接当成data里面的属性用,非常方便,注意没有括号!!!-->
    <td>生日</td><td>{{ getBirthday }}</td>
   </tr>
   <tr>
    <td>年龄</td><td>{{ age }}</td>
   </tr>   
   <tr>
    <td>地址</td><td>{{ address }}</td>
   </tr>
  </table>
 </p>

 <!-- 添加下面这行代码,动态增加 年龄,页面会有怎样的变化呢?? -->
 <button type="button" onclick="app.age+=1;" >加加</button>
 <script>
  var app = new Vue({     
   el: &#39;#app&#39;,        
   data: {          
    birthday: 914228510514,   // 这是一个日期对象的值:1998年11月1日
    age: 19,
    address: &#39;北京昌平区龙泽飞龙&#39;
   },
   computed: {
    // 把日期换成 常见规格格式的字符串。
    getBirthday: function () {
     var m = new Date(this.birthday);
     return m.getFullYear() + &#39;年&#39; + m.getMonth() +&#39;月&#39;+ m.getDay()+&#39;日&#39;;
    }
   }
  });
 </script>
</body>
</html>
Copy after login

11. 双向数据绑定

上面的例子我们大多讲的是单向的 js对象向 HTML数据进行绑定,那HTML怎样向js进行反馈数据呢? HTML中只有表达能接受用户的输入,最简单的演示双向绑定的就是文本框了。

Vue提供了一个新的指令:v-model进行双向数据的绑定,注意不是v-bind。

<!DOCTYPE html> 
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Vue入门之htmlraw</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <p id="app">
  <!-- v-model可以直接指向data中的属性,双向绑定就建立了 -->
  <input type="text" name="txt" v-model="msg">
  <p>您输入的信息是:{{ msg }}</p>
 </p>
 <script>
  var app = new Vue({     
   el: &#39;#app&#39;,        
   data: {          
    msg: &#39;双向数据绑定的例子&#39;
   }
  });
 </script>
</body>
</html>
Copy after login

最终的结果就是:你改变input文本框的内容的时候,p标签中的内容会跟着进行改变,哇是不是很神奇呢...

关于其他表单的绑定的语法我就不赘述了,还是参考官网吧,我这里大部分例子也是来自官网。

12. 数据绑定总结

vue提供了大量的绑定的语法和方法,非常方便我们进行数据的绑定,尤其它是双向的数据绑定,极大的减少了我们dom操作的麻烦程度。可能你越来越喜欢它了吧...

Github地址:源码下载

其他详情请参考:http://aicoder.com/vue/preview/all.html

""

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

有关Vue高阶组件的运用

使用JavaScript实现比异步更好的解决方法?

通过Node.js使用Koa进行项目搭建

The above is the detailed content of Detailed introduction to Vue data binding. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template