Vue is a set of progressive frameworks for building user interfaces.

Template rendering

# "Mustache" syntax {{}} text interpolation:<span>Message: {{MSG}}</span> The MSG property on the bound data object is changed, and the contents of the interpolation are updated.# v-once can perform interpolation once, when the data changes, the content of the interpolation is not updated.<span v-once> Will not change: {{MSG}}</span>#{{}} interprets the data as plain text, not HTML code. To output real HTML, you need to use the V-HTML directive:
<p>Using v-html directive: <span v-html="rawHtml"></span></p> ! Dynamically rendered HTML can lead to XSS attacks.#v-bind/':' : bind HTML features
<div v-bind:id="dynamicId"></div>
Copy the code

Computed attribute computed

Type: {[key: string] : Function | {get: the Function,set: Function } }

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'}, computed: {// Calculate the getter reversedMessage for attributes:function() {// 'this' points to the VM instancereturn this.message.split(' ').reverse().join(' ')}}})Copy the code

Calculate the property cache vs method

Type: {[key: string] : Function | {get: the Function,set: Function}} to achieve the same effect by calling methods in expressions: <p>Reversed message:"{{ reversedMessage() }}"Methods: {reversedMessage:function () {
    return this.message.split(' ').reverse().join(' 'Calculated properties are cached based on their dependencies. A calculated property is reevaluated only if its associated dependencies change. This means that as long as the Message has not changed, multiple visits to the reversedMessage computed property will immediately return the previous computed result without having to execute the function again. By contrast, the calling method will always execute the function again whenever a rerender is triggered. Why do we need caching? Suppose we have A computationally expensive property, A, that iterates through A large array and performs A large number of computations. And then we might have other computational properties that depend on A. Without caching, we would inevitably execute A's getter multiple times! If you don't want caching, use methods instead.Copy the code

Compute properties vs. listen properties

Type: {[key: string] : Function | {get: the Function,set: Function}} 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. Consider this example: <div id="demo">{{ fullName }}</div>
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' '+ val}}}) the above code is imperative and repetitive. Compare this to the version of the calculated attribute: var vm = new Vue({el:'#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' '+ this.lastName}}}) computes only getters by default, but you can provide a setter if you want: //... computed: { fullName: { // getter get:function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } } // ... Now run vm. FullName = again'John Doe'The setter is called, and vm.firstName and vm.lastName are updated accordingly.Copy the code

The listener watch

This approach is most useful when asynchronous or expensive operations need to be performed when data changes. Example: <div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question"> </p> <p>{{ answer }}</p> </div> <! Because the ecosystem of AJAX libraries and common tools is already quite rich, the Vue core code is not duplicated --> <! Provide these features to keep things lean. This 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>
var watchExampleVM = new Vue({
  el: '#watch-example',
  data: {
    question: ' ',
    answer: 'I cannot give you an answer until you ask a question! '}, watch: {// If 'question' changes, this function will run question:function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing... 'This.getanswer ()}}, methods: {// '_. Debounce' is a function that limits the frequency of operations by Lodash. // In this example, we want to limit the frequency of access to yesNo. WTF/API // AJAX requests will not be sent until the user has entered. To learn more about the // '_.debounce' function (and its close relatives' _.throttle '), // see https://lodash.com/docs#debounce
    getAnswer: _.debounce(
      function () {
        if (this.question.indexOf('? ') === -1) {
          this.answer = 'Questions usually contain a question mark. ; -) '
          return
        }
        this.answer = 'Thinking... '
        var vm = this
        axios.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. 'In this example, using the watch option allows us to perform an asynchronous operation (accessing an API), limiting how often we can perform that operation, And set the intermediate state before we get the final result. These are all things you can't do with computed properties.Copy the code

Lifecycle hook

All lifecycle hooks automatically bind this context to the instance, so you can access data and perform operations on properties and methods. This means that you cannot define a lifecycle method using arrow functions (e.g. Created: () => this.fetchtodos ()). This is because the arrow function is bound to the parent context, so unlike what you would expect from a Vue instance, the behavior of this.fetchTodos is undefined.# beforeCreate type: FunctionAfter instance initialization, data Observer and Event/Watcher events are called before configuration.# created type: FunctionCalled immediately after the instance is created. In this step, the instance completes the configuration of data Observer, property and method operations, and watch/ Event event callbacks. However, the mount phase hasn't even started yet,$elProperty is not currently visible.# beforeMount type: FunctionCalled before the mount begins: The associated render function is called for the first time. This hook is not called during server-side rendering.# mounted Type: FunctionEl Specifies the newly created VM.$elReplace and mount the hook to the instance. If the root instance mounts an element within a document, the VM is called when Mounted.$elIt's also in the document. Note that Mounted does not promise that all child components will also be mounted together. If you want to wait until the entire view is rendered, use VM.$nextTickReplace mounted: mounted:function () {
  this.$nextTick(function() {// Code that will run only after the // entire view has been rendered})} This hook will not be called during server-side rendering.# beforeUpdate type: FunctionCalled when data is updated and occurs before the virtual DOM is patched. This is a good place to access the existing DOM before updating, such as manually removing event listeners that have been added. This hook is not called during server-side rendering because only the initial rendering takes place on the server side.# updated type: FunctionThis hook is called after the virtual DOM is re-rendered and patched due to data changes. When this hook is called, the component DOM has been updated, so you can now perform DOM-dependent operations. In most cases, however, you should avoid changing status in the meantime. If you want to change state accordingly, it is usually best to use computed properties or Watcher instead. Note that updated does not promise that all child components will also be redrawn together. If you want to wait until the entire view is redrawn, use VM.$nextTick13. Updated:function () {
  this.$nextTick(function() {// Code that will run only after the // entire view has been re-rendered})} This hook will not be called during server-side rendering.# activated type: FunctionCalled when the keep-alive component is activated. This hook is not called during server-side rendering.# deactivated type: FunctionCalled when the keep-alive component is disabled. This hook is not called during server-side rendering.# beforeDestroy Type: FunctionCalled before instance destruction. At this step, the instance is still fully available. This hook is not called during server-side rendering.Destroyed type: FunctionCalled after the Vue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed. This hook is not called during server-side rendering.ErrorCaptured (2.5.0+ New) Type: Err: Error, VM: Component, info: string =>? booleanCalled when an error from a descendant component is caught. The hook receives three parameters: the error object, the component instance where the error occurred, and a string containing information about the source of the error. This hook can returnfalseTo prevent further upward propagation of the error. You can modify the state of a component in this hook. It is therefore important to short-circuit something else in the template or render function to prevent the component from going into an infinite render loop when an error is caught. Error propagation rules By default, if the global config.errorHandler is defined, all errors will still be sent to it, so these errors will still be reported to a single analysis service place. If there are multiple errorCaptured hooks in a component's descendant or parent slave links, they will be recalled one by one by the same error. If the errorCaptured hook throws an error itself, both the new error and the one that was caught are sent to the global config.errorHandler. An errorCaptured hook returnsfalseTo stop the error from propagating upward. Essentially saying "This error has been fixed and should be ignored". It prevents errorCaptured hooks and the global config.errorHandler that are triggered by this error.Copy the code