Vuejs (7)---computed properties and listeners

Source: Internet
Author: User

Tag: Its length each executes the HTM multiple SDE Ajax div

Compute properties and listenersI. Overview Calculated Properties

Expressions within templates are convenient, but they are designed for simple operations. Putting too much logic into a template can make the template too heavy and difficult to maintain. For example:

<id= "Example">  {{message.split ('). Reverse (). Join (')} }</div>

In this place, the template is no longer a simple declarative logic. You have to look at it for a while to realize that this is the flip string that you want to display message the variable . When you want to refer to the flip string here more than once in a template, it becomes more difficult to handle.

So, for any complex logic, you should use computed properties.

 Basic Examples
 <  div  id  = "Example"   >  <  p  >  Original message: "{{message}}" </ p  Span style= "color: #0000ff;" >>  <  p  >  Computed Reversed message: "{{reversedmessage}}" </ p  >  </ div  >  
var New Vue ({  ' #example ',  data: {    ' Hello '  },  computed: {    //  the Getter function () for the computed attribute      () {      //  ' This ' points to the VM instance c19/>returnthis. Message.split ("). Reverse (). Join (')}}}  )

Results:

Here we declare a computed property reversedMessage . The function we provide will be used vm.reversedMessage as the Getter function for the property

// = ' Olleh 'vm.message = ' Goodbye '// = ' Eybdoog '

You can bind a computed property in a template just as you would a normal property. Vue knows vm.reversedMessage vm.message The dependencies, so when vm.message A change occurs, all dependent vm.reversedMessage bindings are updated. And best of all, we've created this dependency in a declarative way: The Getter function that calculates the property has no side-effect (side effect), which makes it easier to test and understand.

Second, calculate the attribute cache vs Method

You may have noticed that we can achieve the same effect by invoking a method in an expression

< P > Reversed message: "{{reversedmessage ()}}"</p>
// in the component methods: {  function  () {    returnthis. Message.split ("). Reverse (). Join (')  }}

We can define the same function as a method instead of a computed property. The final result of the two approaches is indeed exactly the same. However, the difference is that the computed properties are cached based on their dependencies. a computed property is evaluated only if its dependent dependency has changed. This means that as long as message there is no change, multiple accesses to reversedMessage the computed property will immediately return the previous calculation without having to execute the function again.

This also means that the following computed property will no longer be updated because Date.now() it is not a reactive dependency

computed: {  function  () {    return  date.now ()  }}

In contrast, the calling method will always execute the function again whenever a re-render is triggered.

Why do we need a cache?

Let's say we have a computational property A that has a large performance overhead, it needs to traverse a huge array and do a lot of calculations. Then we may have other computed properties that depend on A. If there is no cache, we will inevitably execute the getter! of a many times If you don't want to have a cache, replace it with a method.

third, calculate properties vs Listen properties

Vue provides a more general way to observe and respond to data changes on the Vue instance: Listening Properties . When you have some data that needs to change as other data changes, you can easily abuse watch It-especially if you've used AngularJS before. However, it is usually better to use a computed property instead of a command-style watch callback.

Consider this example

<id= "Demo">{{fullName}}</div> 
var New Vue ({  ' #demo ',  data: {    ' foo '    , ' Bar ',    ' foo bar '   },  watch: {    function  (val) {       This] . LastName    },    function  (val) {      this]. FirstName + ' + val}}}  )

The above code is imperative and repetitive. Compare it to the version of the computed property:

var New Vue ({  ' #demo ',  data: {    ' Foo '    , ' Bar '  },  computed: {     function () {      returnthis. lastName}}}  )

is not much better.

Four, the setter of the calculated attribute

Calculation properties are only getter by default, but you can also provide a setter when needed

// ...computed: {fullName: {//GetterGetfunction () {      return  This. FirstName + "+ This. LastName},//SetterSetfunction(newvalue) {varnames = Newvalue.split (")       This. FirstName = Names[0]       This. LastName = Names[names.length-1]    }  }}// ...

The vm.fullName = ‘John Doe‘ setter will be called when vm.lastName it is run again, and it will be updated accordingly. vm.firstName

v. Listeners

Although a computed property is more appropriate in most cases, a custom listener is sometimes required. That's why Vue watch provides a more general way to respond to changes in data with options. This approach is most useful when you need to perform asynchronous or expensive operations when data changes.

For example:

<DivID= "Watch-example">  <P>Ask a yes/no question:<inputV-model= "question">  </P>  <P>{{Answer}}</P></Div>
<!--because the ecology of AJAX libraries and common tools is already quite rich, the Vue core code is not duplicated--><!--provide these features to keep it streamlined. It also gives you the freedom to choose the tools you're more familiar with. --><script src= "Https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js" ></script>< Script src= "Https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js" ></script><script>varWATCHEXAMPLEVM =NewVue ({el:' #watch-example ', data: {question:‘‘, Answer:' I cannot give a answer until you ask a question! '}, watch: {//if ' question ' changes, this function will runQuestionfunction(Newquestion, oldquestion) { This. Answer = ' Waiting for your to stop typing ... ' This. Getanswer ()}}, methods: {//' _.debounce ' is a function that restricts the frequency of operation by Lodash.     //In this example, we want to limit the frequency of access to Yesno.wtf/api    //AJAX requests are not issued until the user has finished typing. Want to learn more about    //knowledge of the ' _.debounce ' function (and its close relatives ' _.throttle '),    //please refer to: https://lodash.com/docs#debouncegetanswer: _.debounce (function () {        if( This. Question.indexof ('? ') = = =-1) {           This. Answer = ' Questions usually contain a question mark. ;-)‘return        }         This. Answer = ' thinking ... 'varVM = ThisAxios.get (' Https://yesno.wtf/api '). Then (function(response) {Vm.answer=_.capitalize (Response.data.answer)}) .Catch(function(Error) {Vm.answer= ' error! Could not reach the API. ' +Error}) },      //This is the number of milliseconds we wait to determine the user's stop input500    )  }})</script>

Result: When there is no input? Number, then the following is displayed:

Output "yes" or "no" when there is a.

Specific case effect Address: listener

In this example, the use watch of options allows us to perform asynchronous operations (Access an API), limit how often we do that, and set the intermediate state before we get the final result. These are all computed properties that cannot be done.

think too much, do too little, the middle of the gap is trouble, or to do, or don't think Lieutenant "16"

Vuejs (7)---computed properties and listeners

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.