Home > Web Front-end > JS Tutorial > body text

Some important knowledge points in Vue

小云云
Release: 2018-02-11 11:14:23
Original
2149 people have browsed it

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 v-html="rawHtml"></span></p>
Copy after login

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()
  }
}
Copy after login

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> 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> element.

<template v-if="ok">  <h1>Title</h1>  <p>Paragraph 1</p>  <p>Paragraph 2</p></template>
Copy after login

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` 不是响应式的
Copy after login
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'})
Copy after login
See for details: Here

uses

methods method<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;li v-for=&quot;n in even(numbers)&quot;&gt;{{ n }}&lt;/li&gt;</pre><div class="contentsignin">Copy after login</div></div>## 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 v-for="item in items" :key="item.id"></my-component>
Copy after login
For details, see: here

.once

Event modifier (new in 2.1.4)
<!-- 点击事件将只会触发一次 --><a v-on:click.once="doThis"></a>
Copy after login

.once

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

is

FeaturesDue to some limitations of some dom elements themselves,

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

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

    <div id="app">
      <div>I like money!</div>
      <table></table>
    </div>
    Copy after login
    If you want to parse it correctly, you need to use the
    is

    attribute .

    <div id="app">
      <table>
        <tr is="money"></tr>
      </table>
    </div>
    Copy after login
    This way the dom will be parsed correctly.

    <div id="app">
      <table>
         <tbody>
            <div>I like money!</div>
         </tbody>
      </table>
    </div>
    Copy after login

    具体见:这里

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

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

    todo: {
      text: 'Learn Vue',
      isComplete: false}
    Copy after login

    然后:

    <todo-item v-bind="todo"></todo-item>
    Copy after login

    将等价于:

    <todo-item
      v-bind:text="todo.text"
      v-bind:is-complete="todo.isComplete"></todo-item>
    Copy after login

    具体见: 这里

    非 Prop 特性的替换与合并

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

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

    具体见: 这里

    Props的一般绑定和动态绑定

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

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

    显示:

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

    一般绑定:

    // 父组件<!-- 在 HTML 中使用 kebab-case --><child my-message="hello!"></child>
    
    子组件获得的是: 字符串 'hello!'
    Copy after login

    具体见:这里

    .sync 修饰符(2.3.0+新增)

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

    <comp :foo.sync="bar"></comp>
    Copy after login

    会被扩展为:

    <comp :foo="bar" @update:foo="val => bar = val"></comp>
    Copy after login

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

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

    有点类似与 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
      },  // ...})
    Copy after login
    <my-checkbox v-model="foo" value="some value"></my-checkbox>
    Copy after login

    上述代码等价于:

    <my-checkbox  :checked="foo"
      @change="val => { foo = val }"
      value="some value"></my-checkbox>
    Copy after login

    具体见:这里

    插槽内容分发

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

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

    父组件模板:

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

    渲染结果:

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

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

    具体见:这里

    动态组件

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

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

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

    具体见:这里

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

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

    Vue.component('terms-of-service', {
      template: '\    <div v-once>\      <h1>Terms of Service</h1>\      ...很多静态内容...\    </div>\  '})
    Copy after login

    具体见:这里

    混合(mixins)的合并策略

    周期钩子的合并策略

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

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

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

    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"
    Copy after login

    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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!