Expressions inside templates are specifically traversed, but they are designed for simple operations, and putting too much logic into templates can make them too complex to maintain

<p> <! -- Binding expression --> <! {{course. Length +'door'}} -- > <! -- Calculate attributes --> <! {{total}} --> <! {{totalCount}} </p><script>
    const app = new Vue({
        computed: {
            total() {
            return this.courses.length + 'door'}},// The following does not work because it is not triggered during initialization
// watch: {
    // courses(newValue, oldValue) {
    	//this.totalCount = newValue.length + 'gate'}}})</script>
Copy the code
  • Evaluate properties vs listeners
  • Different data processing scenarios, listeners are suitable for one data affecting multiple data, and computational properties are suitable for one data affected by multiple data
  • The calculated property is cacheable and the calculated value will not be repeated if it does not change
  • The listener option provides a more generic way to perform asynchronous or expensive operations

How is the magic template syntax implemented

At the bottom of the implementation, VUE compiles templates into virtual DOM rendering functions. Combined with the response system, VUE can intelligently calculate how many components need to be rerendered and minimize DOM operations

// Output vue to take a look at our generated render function
console.log(app.$options.render)
Copy the code
/ / that it looks like (function anonymous () {with (this) {return _c (' div '{attrs: {" id ":" app "}}, [_c (h2, {attrs: {"title":title}},[_v("\n "+_s(title)+"\n ")]),_v(" "),_c('input',{directives:[{name:"model",rawName:"v-model",value: (course),expression:"course"}],attrs:{"type":"text"},domProps:{"value": (course)},on:{"keydown":function($event) {if(!$event.type.indexOf('key')&&_k($event.keyCode,"enter",13,$event.key,"Enter" ))return null;return addCourse($event)},"input":function($event) {if($event.target.composing)return;course=$event.target.value}}}),_v(" "), _c (' button '{on: {" click ": addCourse}}, [_v (" new curriculum")]), _v (" "), (courses. The length = = 0)? _c (' p', [_v (" without any course information ")]) : _e (), _v (" "),_c('ul',_l((courses),function(c){return _c('li',{class:{active: (selectedCourse === c)},on:{"click":function($event){selectedCourse = c}}}, [_v(_s(c))])}),0)])} })Copy the code
  • conclusion

Vue uses its compiler to compile the template into a rendering function, executes the rendering function again when the data changes, and compares the results of the two executions to determine the DOM manipulation to be done. The magic in the template is realized