vue3 learning record I

Current version 3.2.25, official website address https://v3.cn.vuejs.org/guide

install

Import the latest version in the form of CDN package for development and use

<script src="https://unpkg.com/vue@next"></script>

npm installation

# Latest stable version
$ npm install vue@next
# Single file component compilation plug-in
$ npm install -D @vue/compiler-sfc

Command line tool (CLI)

# Globally install the latest version of
$ npm install -g @vue/cli
# Project upgrade
$ vue upgrade --next

Build with Vite (official recommendation)

Using npm:

# npm 6.x
$ npm init vite@latest <project-name> --template vue

# npm 7 +, additional double dashes are required
$ npm init vite@latest <project-name> -- --template vue

$ cd <project-name>
$ npm install
$ npm run dev

Get started quickly

Create an application instance

Each Vue application starts by creating a new application instance with the createApp function:

# Same vue2 different creation method
const app = Vue.createApp({
  /* option */
})

interpolation

// The most common form of data binding is text interpolation using "Mustache" (double brace) syntax
<span>Message: {{ msg }}</span>
//By using the v-once instruction, perform one-time interpolation,
//When the data changes, the content at the interpolation will not be updated, affecting the current and future child nodes
<span v-once>This will not change: {{ msg }}</span>
# Use the original HTML v-html Directive:
<span v-html="rawHtml"></span>

Instruction v-bind of binding element

Instructions are prefixed v-, indicating that they are special attribute s provided by Vue.

# The v-bind dynamic binding element dynamicId is a variable 
//If the bound value is null or undefined,
//Then the attribute will not be included in the rendered element.
<div v-bind:id="dynamicId"></div>

v-bind abbreviation

<!-- Complete grammar -->
<a v-bind:href="url"> ... </a>

<!-- abbreviation -->
<a :href="url"> ... </a>

<!-- Abbreviations for dynamic parameters -->
<a :[key]="url"> ... </a>

Using JavaScript expressions

For all data bindings, Vue JS provides full JavaScript expression support.

{{ number + 1 }}

{{ ok ? 'YES' : 'NO' }}

{{ message.split('').reverse().join('') }}
//Each binding can contain only a single expression
<div v-bind:id="'list-' + id"></div>

Instruction of binding element v-on

v-on binding for events

<div id="event-handling">
  <p>{{ message }}</p>
  <button v-on:click="reverseMessage">reversal Message</button>
  <button @click="say('what',$event)">Say what</button>
</div>
#v-on:click binding mouse click events
const EventHandling = {
  data() {
    return {
      message: 'Hello Vue.js!'
    }
  },
  methods: {
    reverseMessage() {
      this.message = this.message
        .split('')
        .reverse()
        .join('')
    }
  }
}

Vue.createApp(EventHandling).mount('#event-handling')

v-on abbreviation

<!-- Complete grammar -->
<a v-on:click="doSomething"> ... </a>

<!-- abbreviation -->
<a @click="doSomething"> ... </a>

<!-- Abbreviations for dynamic parameters -->
<a @[event]="doSomething"> ... </a>

Bidirectional binding instruction v-model

The v-model instruction creates a two-way data binding on the form input, textarea, and select elements
text and textarea elements use value property and input events;
checkbox and radio use checked property and change events;
The select field takes value as a prop and change as an event.

<!-- When selected,`picked` As string "a" -->
<input type="radio" v-model="picked" value="a" />

<!-- `toggle` by true or false -->
<input type="checkbox" v-model="toggle" />

<!-- When the first option is selected,`selected` As string "abc" -->
<select v-model="selected">
  <option value="abc">ABC</option>
</select>

<input type="checkbox" v-model="toggle" true-value="yes" false-value="no" />
<!-- In“ change"Sometimes not“ input"Update when -->
<input v-model.lazy="msg" />
//Automatically convert the user's input value to numeric type
<input v-model.number="age" type="text" />
//Automatically filter the first and last blank characters entered by the user
<input v-model.trim="msg" />

Conditional v-if

Vue automatically applies transition effects when inserting / updating / removing elements.

//Inserts / removes elements based on the true or false value of the expression
<h1 v-if="awesome">Vue is awesome!</h1>

<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

v-show

v-show simply switches the display of elements
Note that v-show does not support elements or v-else.

<h1 v-show="ok">Hello!</h1>

Loop v-for

v-if and v-for are referenced together. Pay attention to using v-if first, which means that v-if will not have access to variables in v-for

<div id="list-rendering">
  <ol>
    <li v-for="(todo, index) in todos" :key="index">
      {{index}}-{{ todo.text }}
    </li>
  </ol>
</div>
const ListRendering = {
  data() {
    return {
      todos: [
        { text: 'Learn JavaScript' },
        { text: 'Learn Vue' },
        { text: 'Build something awesome' }
      ]
    }
  }
}

Vue.createApp(ListRendering).mount('#list-rendering')

dynamic parameter

JavaScript expressions are used in instruction parameters by enclosing them in square brackets:

//Note that there are some constraints on the way parameter expressions are written
<a v-bind:[attributeName]="url"> ... </a>
//Similarly, you can use dynamic parameters to bind the handler function for a dynamic event name:
<a v-on:[eventName]="doSomething"> ... </a>
//When using a template in DOM, this code will be converted to 'v-bind:[someattr]'.
//The code will not work unless there is a property named "someattr" in the instance.
<a v-bind:[someAttr]="value"> ... </a>

Agree on the value of the dynamic parameter. The dynamic parameter is expected to find a string, with the exception of null. This special null value can be used to explicitly remove the binding.

Modifier

Event modifier

.stop
.prevent
.capture
.self
.once
.passive

<!-- Prevent click events from continuing to bubble -->
<a @click.stop="doThis"></a>

<!-- Submitting an event no longer reloads the page -->
<form @submit.prevent="onSubmit"></form>

<!-- Modifiers can be concatenated -->
<a @click.stop.prevent="doThat"></a>

<!-- Only modifiers -->
<form @submit.prevent></form>

<!-- Use event capture mode when adding event listeners -->
<!-- That is, events triggered by internal elements are processed here first, and then handed over to internal elements for processing -->
<div @click.capture="doThis">...</div>

<!-- Only when event.target Is the handler function triggered when the current element itself -->
<!-- That is, the event is not triggered from an internal element -->
<div @click.self="doThat">...</div>

<!-- Default behavior for scrolling events (Rolling behavior) Will trigger immediately,   -->
<!-- Without waiting `onScroll` Done,                    -->
<!-- To prevent it from containing `event.preventDefault()` Situation  -->
<div @scroll.passive="onScroll">...</div>

This The passive modifier can especially improve the performance of the mobile terminal.
Don't take it passive and Use with prevent passive will tell the browser that you don't want to block the default behavior of the event.

Key modifier

Vue provides aliases for the most commonly used keys:
.enter
.tab
. delete (capture delete and backspace keys)
.esc
.space
.up
.down
.left
.right

<!-- Only in `key` yes `Enter` Time call `vm.submit()` -->
<input @keyup.enter="submit" />
<input @keyup.page-down="onPageDown" />

System modifier
.ctrl
.alt
.shift
.meta

<!-- Alt + Enter -->
<input @keyup.alt.enter="clear" />

<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>

. exact modifier
The. exact modifier allows you to control events triggered by a precise combination of system modifiers.

<!-- even if Alt or Shift It is also triggered when pressed together -->
<button @click.ctrl="onClick">A</button>

<!-- Yes and only Ctrl Triggered when pressed -->
<button @click.ctrl.exact="onCtrlClick">A</button>

<!-- Triggered when no system modifier is pressed -->
<button @click.exact="onClick">A</button>

Mouse button modifier
.left
.right
.middle
These modifiers restrict the handler to respond only to specific mouse buttons.

Component application construction

Component system is another important concept of Vue. Almost any type of application interface can be abstracted into a component tree:

Similar usage

//props transfer parameters
const TodoItem = {
  props: ['todo'],
  template: `<li>{{ todo.text }}</li>`
}
// the other one
<div id="todo-list-app">
  <ol>
     <!--
      Now we're for everyone todo-item provide todo object
      todo Objects are variables, that is, their contents can be dynamic.
      We also need to provide one for each component“ key"´╝îLater
      Explain in detail.
    -->
    <todo-item
      v-for="item in groceryList"
      v-bind:todo="item"
      v-bind:key="item.id"
    ></todo-item>
  </ol>
</div>
const TodoItem = {
  props: ['todo'],
  template: `<li>{{ todo.text }}</li>`
}

const TodoList = {
  data() {
    return {
      groceryList: [
        { id: 0, text: 'Vegetables' },
        { id: 1, text: 'Cheese' },
        { id: 2, text: 'Whatever else humans are supposed to eat' }
      ]
    }
  },
  components: {
    TodoItem
  }
}

const app = Vue.createApp(TodoList)

app.mount('#todo-list-app')

Application description

Component instance property

const app = Vue.createApp({
  data() {
    return { count: 4 }
  }
})

const vm = app.mount('#app')

console.log(vm.count) // => 4

There are various other component options. You can add user-defined properties to component instances, such as methods, projects, computed, project and setup.

Life cycle hook

Vue.createApp({
  data() {
    return { count: 1}
  },
  created() {//Do not use the arrow function () here = > {}
    // `this ` points to the vm instance
    console.log('count is: ' + this.count) // => "count is: 1"
  }
})

There are also other hooks that are invoked at different stages of the instance life cycle, such as mounted, updated, and unmounted.

Life cycle diagram

Click to view
[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-l6sohcec-1645882038922)( https://v3.cn.vuejs.org/images/lifecycle.svg#pic_center ])]

Calculate properties and listeners

<div id="computed-basics">
  <p>Has published books:</p>
  <span>{{ publishedBooksMessage }}</span>
</div>

Vue.createApp({
  data() {
    return {
      author: {
        name: 'John Doe',
        books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
        ]
      }
    }
  },
  computed: {
    // Calculate the getter of the property
    publishedBooksMessage() {
      // `this ` points to the vm instance
      return this.author.books.length > 0 ? 'Yes' : 'No'
    }
  }
}).mount('#computed-basics')

Calculate attribute cache vs method
From the end result, the two implementations are exactly the same.
However, the difference is that the calculated attributes will be cached based on their response dependencies.
When re rendering is triggered, the calling method will always execute the function again.

Listener

This approach is most useful when asynchronous or expensive operations need to be performed when data changes.

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question" />
  </p>
  <p>{{ answer }}</p>
</div>

<!-- because AJAX The ecology of libraries and general tools has been quite abundant, Vue The core code is not duplicated -->
<!-- Provide these capabilities to keep it lean. It also gives you the freedom to choose tools you are more familiar with. -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script>
  const watchExampleVM = Vue.createApp({
    data() {
      return {
        question: '',
        answer: 'Questions usually contain a question mark. ;-)'
      }
    },
    watch: {
      // This function will execute whenever the question changes
      question(newQuestion, oldQuestion) {
        if (newQuestion.indexOf('?') > -1) {
          this.getAnswer()
        }
      }
    },
    methods: {
      getAnswer() {
        this.answer = 'Thinking...'
        axios
          .get('https://yesno.wtf/api')
          .then(response => {
            this.answer = response.data.answer
          })
          .catch(error => {
            this.answer = 'Error! Could not reach the API. ' + error
          })
      }
    }
  }).mount('#watch-example')
</script>

Using the watch option allows us to perform an asynchronous operation (access an API) and set a condition to perform the operation. These are things that computational properties cannot do.

Class is bound to Style

When using v-bind for class and style, Vue JS has been specially enhanced. In addition to string, the type of expression result can also be object or array.
Object syntax

<div
  class="static"
  :class="{ active: isActive, 'text-danger': hasError }"
></div>

//variable
<div :class="classObject"></div>
data() {
  return {
    classObject: {
      active: true,
      'text-danger': false
    }
  }
}

//Calculate attribute binding
<div :class="classObject"></div>
data() {
  return {
    isActive: true,
    error: null
  }
},
computed: {
  classObject() {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

Array syntax

<div :class="[activeClass, errorClass]"></div>
data() {
  return {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
}

//Use ternary expressions:
<div :class="[isActive ? activeClass : '', errorClass]"></div>

//Object syntax can also be used in array syntax:
<div :class="[{ active: isActive }, errorClass]"></div>

Bind inline style

Object syntax

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data() {
  return {
    activeColor: 'red',
    fontSize: 30
  }
}

//It is usually better to bind directly to a style object
<div :style="styleObject"></div>
data() {
  return {
    styleObject: {
      color: 'red',
      fontSize: '13px'
    }
  }
}

Array syntax

<div :style="[baseStyles, overridingStyles]"></div>

Auto prefix
When using CSS properties that require a vendor prefix (browser engine prefix) in: style, Vue will automatically detect and add the corresponding prefix

Keywords: Javascript Vue Vue.js

Added by s.steele on Sat, 26 Feb 2022 16:24:58 +0200