search
HomeWeb Front-endJS TutorialSome important knowledge points in Vue

Some important knowledge points in Vue

Feb 11, 2018 am 11:14 AM
Knowledge points

This article mainly shares with you some important knowledge points in Vue, hoping to help everyone.

Don’t use arrow functions on option properties or callbacks

For example

  • created: () => console.log(this.a)

  • vm.$watch('a', newValue => this.myMethod())
    Because the arrow function is bound to the parent context Together, this will not be a Vue instance as you expect, often resulting in Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not Errors such as a function

See for details: here

v-html

Double curly brackets will interpret the data as ordinary text , not HTML code. In order to output real HTML, you need to use the v-html directive:

<p>Using mustaches: {{ rawHtml }}</p><p>Using v-html directive: <span></span></p>

See for details: here

Computed attribute cache vs method

We can define the same function as a method instead of a computed property. The end result is indeed exactly the same both ways. However, the difference is that computed properties are cached based on their dependencies. A computed property is only re-evaluated when its associated dependencies change. This means that as long as the message has not changed, multiple accesses to the reversedMessage calculated property will immediately return the previous calculated result without having to execute the function again.
What does this mean that computed properties are cached based on their dependencies?

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

Although the value of Date.now() keeps changing, it is not watch because it is not a reactive dependency .

For details, see: here

CSS styles automatically add prefixes

When v-bind:style is used when using CSS properties that require adding browser engine prefixes , such as transform, Vue.js will automatically detect and add the corresponding prefix.

See for details: Here

Use v-if conditional rendering grouping on the <template></template> element

Because v-if is an instruction, So it must be added to an element. But what if you want to switch multiple elements? At this point, you can treat an element as an invisible wrapping element and use v-if on it. The final rendering result will not contain the <template></template> element.

<template>  <h1 id="Title">Title</h1>  <p>Paragraph 1</p>  <p>Paragraph 2</p></template>

See for details: here

v-if and v-show and v-for

  • v-if is the operation of adding and removing page elements

  • v-show is the display and hiding of page elements Operation

  • When v-if is used with v-for, v-for has higher priority than v-if.

For details, see: here

Array change detection precautions

Vue cannot detect an array whose mode has changed, so the view update will not be triggered

  • When you use the index to set an item directly, for example: vm.items[indexOfItem] = newValue

  • When When you modify the length of the array, for example: vm.items.length = newLength

##For details, see: here

Object change detection precautions

Vue cannot detect the addition or deletion of object attributes

var vm = new Vue({
  data: {
    a: 1
  }
})// `vm.a` 现在是响应式的vm.b = 2// `vm.b` 不是响应式的
But we can use the

Vue.set(object, key, value) method to embed Add responsive properties to objects. There is also this commonly used method
Object.assign(). When we want to assign multiple new attributes to an object, you should play like this

this.userProfile = Object.assign({}, this.userProfile, {
  age: 27,
  favoriteColor: 'Vue Green'})
See for details: Here

uses

methods method<pre class="brush:php;toolbar:false"></pre> <li>{{ n }}</li>## in v-for

#See for details: Here

components use

v-for

In custom components, you can use

v- like any normal element for

.

<my-component></my-component>
For details, see: here

.once

Event modifier (new in 2.1.4)
<!-- 点击事件将只会触发一次 --><a></a>

.once

can also be used on custom components. For details, see: here

is

FeaturesDue to some limitations of some dom elements themselves,

    , <ol></ol>, <table>, <code><select></select> There are restrictions on the elements allowed to be contained in such elements.

    <div>  <table>    <money></money>  </table>
    </div>Vue.component('txt',{
       template: '<div>I like money!</div>'})new Vue({
      el:'#app'})
    will be parsed into the following dom

    <div>
      <div>I like money!</div>
      <table></table>
    </div>
    If you want to parse it correctly, you need to use the
    is

    attribute .

    <div>
      <table>
        <tr></tr>
      </table>
    </div>
    This way the dom will be parsed correctly.

    <div>
      <table>
         <tbody>
            <div>I like money!</div>
         </tbody>
      </table>
    </div>

    具体见:这里

    将对象的所有属性作为 prop 进行传递

    如果你想把一个对象的所有属性作为 prop 进行传递,可以使用不带任何参数的 v-bind (即用 v-bind 而不是 v-bind:prop-name)。例如,已知一个 todo 对象:

    todo: {
      text: 'Learn Vue',
      isComplete: false}

    然后:

    <todo-item></todo-item>

    将等价于:

    <todo-item></todo-item>

    具体见: 这里

    非 Prop 特性的替换与合并

    • classstyle这两个特性的值都会做合并 (merge) 操作

    • 其他属性(如: type) 则会进行覆盖

    具体见: 这里

    Props的一般绑定和动态绑定

    我们常用的一般是动态绑定:

    // 父组件<child></child>new Vue({  data () {    return {
           parentMsg: '来自父组件的数据'
        }
      }
    })// 子组件Vue.component('child', {  // 在 JavaScript 中使用 camelCase
      props: ['myMessage'],
      template: '<span>{{ myMessage }}</span>'})

    显示:

    <span>来自父组件的数据</span>

    一般绑定:

    // 父组件<!-- 在 HTML 中使用 kebab-case --><child></child>
    
    子组件获得的是: 字符串 'hello!'

    具体见:这里

    .sync 修饰符(2.3.0+新增)

    之前在 2.0 版本中移除后,在 2.3.0 中又加上了,只是调用的逻辑发生了变化,变成了一种语法糖。
    如下代码:

    <comp></comp>

    会被扩展为:

    <comp> bar = val"></comp>

    当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:

    this.$emit('update:foo', newValue)

    有点类似与 v-model

    具体见:这里

    自定义组件的 v-model(2.2.0 新增)

    默认情况下,一个组件的 v-model 会使用 value propinput 事件。这也是之前 v-model 默认绑定的元素 和 事件方法。

    但是到 2.2.0 时候,我们可以通过 model 配置这个两个属性。

    Vue.component('my-checkbox', {
      model: {
        prop: 'checked',    event: 'change'
      },
      props: {
        checked: Boolean,    // 这样就允许拿 `value` 这个 prop 做其它事了
        value: String
      },  // ...})
    <my-checkbox></my-checkbox>

    上述代码等价于:

    <my-checkbox> { foo = val }"
      value="some value"></my-checkbox>

    具体见:这里

    插槽内容分发

    我们不总能遇见我们的组件中包含了哪些元素,这时候我们在开发组件的时候,需要让这部分内容自定义。
    假定 my-component 组件有如下模板:

    <div>
      <h2 id="我是子组件的标题">我是子组件的标题</h2>
      <slot>
        只有在没有要分发的内容时才会显示。
      </slot>
    </div>

    父组件模板:

    <div>
      <h1 id="我是父组件的标题">我是父组件的标题</h1>
      <my-component>
        <p>这是一些初始内容</p>
        <p>这是更多的初始内容</p>
      </my-component>
    </div>

    渲染结果:

    <div>
      <h1 id="我是父组件的标题">我是父组件的标题</h1>
      <div>
        <h2 id="我是子组件的标题">我是子组件的标题</h2>
        <p>这是一些初始内容</p>
        <p>这是更多的初始内容</p>
      </div>
    </div>

    当然还有 具名插槽 、作用域插槽(2.1.0 新增)、slot-scope(2.5.0新增)

    具体见:这里

    动态组件

    通过使用保留的 <component></component> 元素,并对其 is 特性进行动态绑定,你可以在同一个挂载点动态切换多个组件:

    var vm = new Vue({
      el: '#example',
      data: {
        currentView: 'home'
      },
      components: {
        home: { /* ... */ },
        posts: { /* ... */ },
        archive: { /* ... */ }
      }
    })
    <component>  <!-- 组件在 vm.currentview 变化时改变! --></component>

    注意这里的 is 与 之前说的 v-bind:is 别混淆

    具体见:这里

    对低开销的静态组件使用 v-once

    尽管在 Vue 中渲染 HTML 很快,不过当组件中包含大量静态内容时,可以考虑使用 v-once 将渲染结果缓存起来,就像这样:

    Vue.component('terms-of-service', {
      template: '\    <div>\      <h1 id="Terms-of-Service">Terms of Service</h1>\      ...很多静态内容...\    </div>\  '})

    具体见:这里

    混合(mixins)的合并策略

    周期钩子的合并策略

    • 同名钩子函数将混合为一个数组,因此都将被调用

    • 混合对象的钩子将在组件自身钩子 之前 调用

    var mixin = {  created: function () {    console.log('混合对象的钩子被调用')
      }
    }new Vue({
      mixins: [mixin],  created: function () {    console.log('组件钩子被调用')
      }
    })// => "混合对象的钩子被调用"// => "组件钩子被调用"

    methods, components 和 directives 的合并策略

    • 两个对象键名冲突时,取组件对象的键值对

    var mixin = {
      methods: {    foo: function () {      console.log('foo')
        },    conflicting: function () {      console.log('from mixin')
        }
      }
    }var vm = new Vue({
      mixins: [mixin],
      methods: {    bar: function () {      console.log('bar')
        },    conflicting: function () {      console.log('from self')
        }
      }
    })vm.foo() // => "foo"vm.bar() // => "bar"vm.conflicting() // => "from self"

The above is the detailed content of Some important knowledge points in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool