In the last article we learned a brief introduction to Uni-App, a framework for developing all front-end applications using vue.js. In this section we will learn how to use Vue.
Vue profile
Vue (pronounced vju/curliest, similar to View) is a set of progressive frameworks 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 focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.
Vue usage experience
Two-way binding
- Jquery writing
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" SRC = "http://libs.baidu.com/jquery/2.0.0/jquery.min.js" / > < / head > < body > < input type = "text" data - the bind - 0 = name / > < span data-bind-0="name"></span> <script type="text/javascript"> function DataBinder(object_id) { var pubSub = jQuery({}); var data_attr = "bind-" + object_id, message = object_id + ":change"; jQuery(document).on("change", "[data-" + data_attr + "]", function (evt) { var $input = jQuery(this); pubSub.trigger(message, [$input.attr("data-" + data_attr), $input.val()]); }); pubSub.on(message, function (evt, prop_name, new_val) { jQuery("[data-" + data_attr + "=" + prop_name + "]").each(function () { var $bound = jQuery(this); if ($bound.is("input,textarea,select")) { $bound.val(new_val); } else { $bound.html(new_val); }}); }); return pubSub; } function User(uid) { var binder = new DataBinder(uid), user = { attributes: {}, set: function (attr_name, val) { this.attributes[attr_name] = val; binder.trigger(uid + ":change", [attr_name, val, this]); }, get: function (attr_name) { return this.attributes[attr_name]; }, _binder: binder }; return user; } var user = new User(0); user.set("name", "text"); </script> </body> </html>Copy the code
- Vue writing
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <! -- introduction of vue. Js - > < script SRC = "https://cdn.jsdelivr.net/npm/vue/dist/vue.js" > < / script > < / head > < body > <! - two-way binding -- > < div id = "app - 1" > < p > {{MSG}} < / p > < input type = "text" v - model = "MSG" / > < / div > < / body > < script > var = new app Vue ({el: "app - # 1," data: {MSG: "moment in running"}}) < / script > < / HTML >Copy the code
As can be seen from this example, Vue is written very succinct and convenient.
Conditional expression
The code is shown below
<body> <! <div id="app-if"> <! Continue typing appif.seen = false on the console, and you will notice that the previously displayed message disappears. -- > < p v - if = "seen" > see me < / p > < button @ click = "hidden" > point under the {{MSG}} < / button > < / div > < / body > < script > new Vue ({el: "# app - if", Data :{seen:true, MSG :' hidden '}, methods:{hidden(){this.seen = false; This. MSG = 'display '; } } }) </script>Copy the code
The for loop
<body> <div id="app"> <ol> <li v-for="city in citys"> {{city.name}} </li> </ol> </div> </body> <script> new Vue({ El: "# app," data: {citys: [{name: "hefei"}, {name: "tongling city"}, {name: "anqing city"}]}}) < / script >Copy the code
Rendering Html
The < body > < div id = "app" > < p > HTML content: {{rawHtml}} < / p > < p > HTML display: < span v - HTML = "rawHtml" > < / span > < / p > < / div > < / body > <! Double braces interpret the data as plain text, not HTML code. To output real HTML, you need to use the V-HTML directive: --> <script> new Vue({el:"#app", data: {rawHtml: "< a href = '#' > time running < / a > < img SRC =" https://i.loli.net/2021/04/15/3jHaiZg4fUneRQT.gif "/ >"}}) < / script >Copy the code
Html property binding
<body> <div id="app"> <input type="text" v-model="userName" /> <! V-bind works slightly differently for Boolean attributes (which simply exist means the value is true), in this case: <button V-bind :disabled="isButtonDisabled" V-on :click="submit"> </button> <! If isButtonDisabled is null, undefined, or false, the disabled attribute is not even included in the rendered <button> element. --> </div> </body> <! -- Mustache syntax doesn't work on HTML attributes, you should use v-bind: --> <script> new Vue({el:"#app", data: { userName:"", isButtonDisabled:false }, methods:{ submit(){ var _this = this; alert("userName="+_this.userName); _this.isButtonDisabled = true; SetTimeout (function (){alert(" commit successfully "); _this.isButtonDisabled = false; }, 3000); } } }) </script>Copy the code
JavaScript expression
<body> <div id="app"> <div v-bind:id="'list-' + id"></div> <div v-bind:hidden="ok? Display: true or false "> < / div > < p > < span > 1 + 1 = < / span > {{number + 1}} < / p > < div > < span > you ok? {{ ok ? 'yes':'no'}}</span></div> <div>{{message.split('').reverse().join('')}}</div> </div> </body> <! In fact, vue.js provides full JavaScript expression support for all data binding. {{ number + 1 }} {{ ok ? 'YES' : 'NO' }} {{ message.split('').reverse().join('') }} --> <script> new Vue({ el:"#app", data: { id: 1, number:1, ok:true, message:"abcd", hidden:false } }) </script> <! These expressions are parsed as JavaScript in the data scope of the owning Vue instance. One limitation is that each binding can only contain a single expression, so none of the following examples will work. {{if (OK) {return message}}} template expressions are placed in a sandbox and can only access a whitelist of global variables. Examples include Math and Date. You should not attempt to access user-defined global variables in template expressions. -->Copy the code
Calculate attribute
< div id = "example" > brand name: < input type = "text" v - model = "brandName" > < / input > < p > initials: {{firstLetter}} < / p > < / div > < / body > <! You should use computed properties for any complex logic. Vue provides a more general way to observe and respond to changes in data on Vue instances: listening properties. It's easy to abuse Watch when you have some data that needs to change with other data -- especially if you've used AngularJS before. However, it is often better to use computed properties rather than imperative Watch callbacks. <script> var vm = new Vue({el: "#example", data: {brandName:"Adidas",}, // Computed properties computed:{firstLetter:{// Computed properties only have getters by default, but you can provide a setter if you want: get:function () { var brandName = this.brandName; Var firstLetter = brandname.substr (0,1).touppercase (); return firstLetter; }, // In addition, set sets the property, not directly modify the calculation property, but modify its dependencies. Set: function (newValue) {//this.firstLetter = newValue; } } } }) </script>Copy the code
Calculate the property cache vs method
We can define the same function as a method rather than a calculated property. The end result is exactly the same. The difference, however, is that computed attributes are cached based on their reactive dependencies. They are reevaluated only when the associated reactive dependencies change.
Watch the listener
<div id="example"> <input type="text" v-model="brandName"></input> <p> firstLetter :{{firstLetter}}</p> </div> </body> El: "#example", data: {brandName: "Adidas", firstLetter: "}, // count attributes: {brandName: Function (newVal,oldVal) {this.firstletter = newval.substr (0,1).touppercase (); } } }) </script>Copy the code
Watch versus computed
From the flow chart above, we can see the difference between them:
- Watch: Monitors the value of the property, and whenever the value of the property changes, it triggers the execution of a callback function to perform a series of operations.
- Computed: Monitors dependency values. If the dependency values remain the same, it directly reads the cache for reuse, and recalculates only when they change.
In addition, there is a slightly important difference: computed properties cannot perform asynchronous tasks; computed properties must be executed synchronously. This means that computed properties cannot request or perform asynchronous tasks to the server. If an asynchronous task is encountered, it is handed to the listening property. Watch can also detect computed attributes.
V – short for bind
<! <a v-bind:href="url">... </a> <! <a :href="url">... </a> <! <a :[key]="url">... </a>Copy the code
V – on abbreviation
<! <a v-on:click="doSomething"> </a> <! < a@click ="doSomething">... </a> <! - the abbreviation of dynamic parameters (server +) - > < a @ [event] = "doSomething" >... </a>Copy the code
Vue life cycle
<body> <div id="app"> </div> </body> <! Each Vue instance goes through a series of initialization procedures when it is created -- for example, you need to set up data listeners, compile templates, mount the instance to the DOM, and update the DOM when the data changes. Functions called lifecycle hooks are also run along the way, giving users the opportunity to add their own code at different stages. For example, the Created hook can be used to execute code after an instance is created: --> <! There are other hooks called at different points in the instance lifecycle, such as Mounted, updated, and destroyed. The this context of the lifecycle hook points to the Vue instance calling it. --> <script> new Vue({data: {a: "init"}, created: function () {// 'this' points to vm instance alert('a is: ' + this.a) // => "a is: 1" } }) </script>Copy the code
The following figure shows the life cycle of the instance. You don’t have to understand everything immediately, but it will become more valuable as you learn and use it.
Lifecycle hooks: cn.vuejs.org/v2/api/#cre…
componentization
<body> <! Because components are reusable Vue instances, they receive the same options as new Vue, such as Data, computed, Watch, methods, and lifecycle hooks. The only exceptions are root instance-specific options like EL. --> <div id="components-demo"> <button-counter></button-counter> <! - analytical results < div id = "components - demo" > < button > ordered me eight times. < / button > < / div > -- > <! <button-counter></button-counter> </button-counter> <! Note that each component maintains its count independently when the button is clicked. Because every time you use a component, a new instance of it is created. Vue.component('button-counter', </div> </body> <script> {// The data option of a component must be a function // When we define the <button-counter> component, you may notice that its data does not provide an object directly like this: Data: function () {return {count:0}, template: function () {return {count:0}, template: '< button v - on: click = "count++" > o 'clock I {{count}}. < / button > "}); /* In order to be used in templates, these components must first be registered for Vue to recognize. There are two types of registration for components: global and local. So far, our components are only globally registered with Vue.component: Vue.component('my-component-name', {//... options ... }) globally registered components can be used in any newly created Vue root instance (via new Vue) after they are registered, as well as in templates for all children of their component tree. */ new Vue({ el: '#components-demo' }); </script>Copy the code
Component systems are another important concept for Vue because it is an abstraction that allows us to build large applications from small, independent, and often reusable components. If you think about it, almost any type of application interface can be abstracted as a component tree:
reference
Simple two-way data binding with jquery
Vue official document
Explain Vue compute properties and listen properties in detail