1. How to make a variable in vue.js work only once?

There’s a V-once instruction, just use it.

Rendering pure HTML elements in Vue is very fast, but sometimes you may have a component that contains a lot of static content. In these cases, you can ensure that the root element is evaluated only once and then cached, as shown below:

app.component('terms-of-service', {
  template: `
    <div v-once>
      <h1>Terms of Service</h1>
      ... a lot of static content ...
    </div>
  `
})
Copy the code

But be warned:

Don’t overuse this pattern. While this mode can be handy in the rare cases where you need to render a lot of static content, it’s not necessary unless you notice that the previous rendering was slow. In addition, overusing this model can cause a lot of confusion later on. For example, suppose another developer is unfamiliar with V-once or simply missed it in the template. They can spend hours trying to figure out why the template wasn’t updated correctly.

For the following code snippet, if you pass vm.$data. MSG = ‘This is a new string! ‘to update MSG, the interface will not be re-rendered. It works when the V-once is removed.

src\main.js

import { createApp } from 'vue'
import App from './App.vue'

window.vm = createApp(App).mount('#app')
Copy the code

src\App.vue

<template>
  <h1 v-once>{{ msg }}</h1>
</template>

<script>
export default {
  name: 'App'.data() {
    return {
      msg: 'Vue.js 3.x'}; }}</script>
Copy the code

2. How to bind dynamic events and properties?

Vue. Js supports binding dynamic events and properties.

<template>
  <h1 v-once>{{ msg }}</h1>
  <button@ [eventName] ="eventHandler" :[propName] ="propValue">button</button>
</template>

<script>
export default {
  name: 'App'.data() {
    return {
      msg: 'Vue.js 3.x'.eventName: 'click'.propName: 'title'.propValue: 'This is a title'}; },setup() {
    return {
      eventHandler() {
        alert('hahaha'); }}}}</script>
Copy the code

This code snippet runs and the button clicks ‘hahaha’ and binds the button with the title property. Hover over the button to see the title information.

How many lifecycle hook functions does vue.js 3.

The problem couldn’t be simpler. But it seems that many people only know the first 8, some training course teachers also said that only 8, probably the rest of the few used less. There are actually 13 of them.

Option type API Hook inside setup function
beforeCreate Not needed* Functions that are automatically executed before instance generation
created Not needed* A function that is automatically executed after the instance is generated
beforeMount onBeforeMount A function that is automatically executed before the component content is rendered to the page
mounted onMounted A function that is automatically executed after the component content has been rendered to the page
beforeUpdate onBeforeUpdate A function that is executed immediately when data changes
updated onUpdated A function that is automatically executed when the data changes and the page is re-rendered
beforeUnmount onBeforeUnmount A function that is automatically executed before a component is destroyed
unmounted onUnmounted A function that is automatically executed after a component is destroyed
errorCaptured onErrorCaptured Called 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.
renderTracked onRenderTracked Called when tracking the virtual DOM is re-rendered. Hook to receiveDebuggerEventtAs a parameter. This event tells you which action tracks the component and the target object and key for that action.
renderTriggered onRenderTriggered Called when the virtual DOM rerendering is triggered. andrenderTrackedSimilarly, receiveDebuggerEventtAs a parameter. This event tells you what action triggered the rerender, as well as the target object and key for that action.
activated onActivated Called when activated by a component cached by keep-alive.This hook is not called during server-side rendering.
deactivated onDeactivated Called when a component cached by keep-alive is disabled.This hook is not called during server-side rendering.

Note:


when wrapping dynamic components, inactive component instances are cached rather than destroyed. Like
,

is an abstract component: it does not render a DOM element on its own, nor does it appear in the component’s parent chain.

When a component is toggled within

, its Mounted and unmounted lifecycle hooks are not called, but activated and deactivated instead. (This applies to the immediate children of

and all their descendants.)

You can sense the impact of

on the life cycle of its internal components by running the following code snippet and clicking the Toggle button to view the log of the console lifecycle hook:

src\App.vue

<template>
  <button @click="toggle">toggle</button>
  <keep-alive>
    <component :is="currentComponent"></component>
  </keep-alive>
</template>

<script>
import Foo from './components/Foo.vue';
import Bar from './components/Bar.vue';

export default {
  name: 'App'.components: {
    Foo,
    Bar,
  },
  data() {
    return {
      toggleCount: 1.currentComponent: Foo,
    };
  },
  methods: {
    toggle() {
      const arr = [Foo, Bar];
      this.toggleCount += 1;
      this.currentComponent = arr[this.toggleCount % 2]; }},beforeCreate() {
    console.log('beforeCreate');
  },
  created() {
    console.log('created');
  },
  beforeMount() {
    console.log('beforeMount');
    console.log(document.getElementById('app').innerHTML);
  },
  mounted() {
    console.log('mounted');
    console.log(document.getElementById('app').innerHTML);
  },
  beforeUpdate() {
    console.log('beforeUpdate');
    console.log(document.getElementById('app').innerHTML);
  },
  updated() {
    console.log('updated');
    console.log(document.getElementById('app').innerHTML);
  },
  beforeUnmount() {
    console.log('beforeUnmount');
    console.log(document.getElementById('app').innerHTML);
  },
  unmounted() {
    console.log('unmounted');
    console.log(document.getElementById('app').innerHTML); }},</script>
Copy the code

src\components\Foo.vue

<template>
  <h2>foo</h2>
</template>

<script>
export default {
  beforeUnmount() {
    console.log('beforeUnmount');
    console.log(document.getElementById('app').innerHTML);
  },
  unmounted() {
    console.log('unmounted');
    console.log(document.getElementById('app').innerHTML);
  },
  activated() {
    console.log('activated');
    console.log(document.getElementById('app').innerHTML);
  },
  deactivated() {
    console.log('deactivated');
    console.log(document.getElementById('app').innerHTML); }},</script>
Copy the code

src\components\Bar.vue

<template>
  <h2>bar</h2>
</template>
Copy the code

ErrorCaptured hooks are hooks that communicate as follows:

Error propagation rule

  • By default, if globalconfig.errorHandlerAll errors are still sent to it, so these errors are still reported to a single analysis service place.
  • If a component has more than one descendant or parent slave linkerrorCapturedHook, they will be called up one by one by the same error.
  • If thiserrorCapturedThe hook itself throws an error, and both the new error and the original caught error are sent globallyconfig.errorHandler.
  • aerrorCapturedThe hook can returnfalseTo stop the error from propagating upward. Essentially saying “This error has been fixed and should be ignored”. It will prevent anything else from being aroused by the errorerrorCapturedHooks and globalconfig.errorHandler.

ErrorCaptured hooks are called when an error from a descendant component is captured, but they are not triggered when an error is thrown by the component itself.

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 return false to prevent further propagation of the error.

Use of errorCaptured hooks can be seen in the following code snippet:

src\App.vue

<template>
  <Foo></Foo>
</template>

<script>
import Foo from './components/Foo.vue';

export default {
  name: 'App'.components: {
    Foo,
  },
  errorCaptured(. arg) {
    console.log('errorCaptured', arg); }}</script>
Copy the code

src\components\Foo.vue

<template>
  <h2>foo</h2>
</template>

<script>
export default {
  mounted() {
    throw Error(a); }},</script>
Copy the code

4. What’s the difference between methods and attributes?

In the following code snippet, the contents of the computedVal will not be refreshed when the MSG variable is changed by typing vm.$vm. MSG = ‘new String ‘in the console. Values obtained through Method are refreshed.

A calculated property is recalculated only when the reactive variable on which it depends changes, such as when this.count is modified here.

The method calculation is recalculated whenever the component is updated. For example, if vm.$vm. MSG = ‘new string’ changes the MSG variable, the component update is triggered, and method is evaluated again, even though the expression does not depend on the MSG variable.

src\App.vue

<template>
  <h1>{{ msg }}</h1>
  <button@ [eventName] ="eventHandler" :[propName] ="propValue">button</button>
  <div>Compute attributes: {{computedVal}}</div>
  <div>{{caculateMethod()}}</div>
</template>

<script>
export default {
  name: 'App'.data() {
    return {
      msg: 'Vue.js 3.x'.eventName: 'click'.propName: 'title'.propValue: 'This is a title'.count: 1}; },computed: {
    computedVal() {
      return this.count + new Date().getTime(); }},setup() {
    return {
      eventHandler() {
        alert('hahaha'); }}},methods: {
    caculateMethod() {
      return this.count + new Date().getTime(); }},}</script>
Copy the code