VUE3 interview questions and knowledge points, with answers!

What is Vue 3.0? What's new compared to Vue 2.x?

A: Vue 3.0 is the latest version of the Vue.js framework. It brings several new features, including:

  • Composition API: Provides a more flexible logical organization, making components easier to reuse and test.
  • Better performance: Vue 3.0 uses a rewritten responsive system that renders faster and takes less memory.
  • Improved TypeScript support: Vue 3.0 has made improvements in TypeScript, allowing developers to take better advantage of TypeScript's type checking capabilities.

What is the Composition API in Vue 3.0? How is it different from the Options API?

Answer: Composition API is a new API style introduced by Vue 3.0, which provides a more flexible logical organization method and makes components easier to reuse and test. Compared with the Options API, the main differences of the Composition API are:

  • Composition: The Composition API encourages grouping related code together, rather than organizing code by lifecycle functions or options.
  • Reusability: The Composition API allows logic code to be encapsulated into reusable functions for sharing across multiple components.
  • Better type inference: The Composition API allows better use of TypeScript's type inference capabilities, making it easier for developers to write type-safe code.

What improvements have been made to the reactive system in Vue 3.0? Why do these improvements improve performance?

A: The responsive system in Vue 3.0 is a huge improvement over Vue 2.x. Major improvements include:

  • Proxy replaces Object.defineProperty: Vue 3.0 uses Proxy instead of Object.defineProperty to implement a responsive system. Proxy has better performance and also allows dynamic addition and removal of properties on objects.
  • More efficient caching: Vue 3.0 uses a more efficient caching mechanism to reduce the number of repeated calculations.
  • Less memory footprint: Vue 3.0 uses fewer internal objects, reducing memory footprint.

These improvements improve performance because they reduce computation and reduce memory footprint, resulting in faster rendering and a smaller memory footprint.

What is the Teleport component in Vue 3.0? What is it for?

Answer: The Teleport component is a new component introduced by Vue 3.0, which allows the output of the component to be inserted into different positions in the DOM tree. Teleport components can be used to solve the following problems:

  • Modal Box Component: The Teleport component can insert the content of the modal box into the body element in the DOM tree to avoid problems with z-index.
  • Multilingual support: The Teleport component can be used to render translated text in different languages ​​in different places.

What improvements have been made to the v-model directive in Vue 3.0?

A: The v-model directive in Vue 3.0 has some improvements compared to Vue 2.x. Major improvements include:

  • Support custom two-way binding event names: Vue 3.0 allows developers to customize two-way binding event names for different types of form controls, such as checkbox and radio.
  • Support custom value attribute names: Vue 3.0 allows developers to customize value attribute names for different types of form controls, such as the value attribute names of radio and select controls.

What are Suspense components in Vue 3.0? What is it for?

Answer: The Suspense component is a new component introduced by Vue 3.0, which allows a placeholder to be displayed when the asynchronous component is loaded, and the actual content will not be displayed until the asynchronous component is loaded. Suspense components can be used to solve the following problems:

  • Loading state: Suspense components can be used to display a "loading" state when an asynchronous component loads to provide a better user experience.
  • Error handling: Using the Suspense component can display an error message when an asynchronous component fails to load to help users better understand the problem.

What are the other new features in Vue 3.0?

Answer: In addition to the new features mentioned above, Vue 3.0 also introduces some other new features, including:

  • Global API function renaming: Vue 3.0 renames some global API functions to improve readability and consistency.
  • Better TypeScript support: Vue 3.0 has improved support for TypeScript, including better type inference, better type definition files, and more.
  • Improved custom directives: Vue 3.0 allows developers to use the Composition API in custom directives, and provides better documentation and examples to help developers write custom directives.

What is static hoisting in Vue 3.0? What are its advantages?

Answer: Static promotion is a new technology introduced by Vue 3.0, which can perform static analysis on templates during the compilation phase, and advance static nodes to be processed at compile time. Static boosting can bring the following advantages:

  • Faster Rendering: Static boosting reduces code at runtime, resulting in faster rendering.
  • Smaller bundle size: Static promotion can reduce the amount of code generated by compilation, thereby reducing the bundle size.
  • Better maintainability: Static hoisting can improve the readability and maintainability of your code because it makes the code easier to understand and modify.

How to access parent component instance in Vue 3.0?

Answer: In Vue 3.0, developers can access parent component instances in child components by using inject/provide API. Specifically, you can use the provide method in the parent component to provide a value, and use the inject method in the child component to get the value. In this way, the instance of the parent component can be accessed in the child component.

What is the difference between the Teleport component and the Portal component in Vue 3.0?

Answer: Both the Teleport component and the Portal component can be used to render content outside the component tree. Their main differences are:

  • The Teleport component can render content to a specified DOM element, while the Portal component can render content to any position.
  • Teleport components can only be used in the same component tree, while Portal components can be used in different component trees.
  • The Teleport component requires the target element to exist in the DOM, while the Portal component can dynamically create the target element.

Generally speaking, the Teleport component is more suitable for rendering content to existing elements, while the Portal component is more suitable for rendering content to a new location.

In addition, the Portal component has an additional purpose, it can be used to solve z-index hierarchy issues. For example, when using a modal box, the Portal component can render the content of the modal box into the body element to avoid z-index hierarchy issues.

How to access child component instance in Vue 3.0?

Answer: In Vue 3.0, you can use the ref attribute to access child component instances. refSpecifically, you can use attributes in the parent component to specify a name for the child component, and then use the name to access the instance of the child component. For example:

<template>
  <child-component ref="child"></child-component>
</template>

<script>
export default {
  mounted() {
    const childInstance = this.$refs.child;
    // 访问子组件实例
  }
}
</script>

In Vue 3.0, how to dynamically create components?

Answer: In Vue 3.0, createAppfunctions and defineComponentfunctions can be used to dynamically create components. Specifically, functions can be used defineComponentto define a component, and createAppfunctions to create a Vue application. Then, use methods in the application componentto register the component and mount it on a DOM element. For example:

import { createApp, defineComponent } from 'vue';

const MyComponent = defineComponent({
  template: '<div>{
   
   { message }}</div>',
  data() {
    return {
      message: 'Hello, world!'
    };
  }
});

const app = createApp({});
app.component('my-component', MyComponent);
app.mount('#app');

How to use the composition API in Vue 3.0?

Answer: In Vue 3.0, you need to follow the steps below to write component code using Composition API:

  1. Import reactive, ref, computedand other functions;
  2. Define components using functions, and use functions defineComponentin them ;setup
  3. Use the Composition API to write logic codes in setupfunctions, such as defining data, computing properties, methods, etc.;
  4. Use the defined data and methods in the template.

For example:

<template>
  <div>{
   
   { count }}</div>
</template>

<script>
import { defineComponent, ref } from 'vue';

export default defineComponent({
  setup() {
    const count = ref(0);

    function increment() {
      count.value++;
    }

    return { count, increment };
  }
});
</script>

How does the reactivity system work in Vue 3.0?

Answer: The responsive system in Vue 3.0 is implemented based on ES6 Proxy. When we define a responsive object, Vue converts it into a Proxy object and intercepts operations such as reading and assigning the object. When the object is accessed or changed, Vue will automatically trigger the related update operation to update the view.

Specifically, the responsive system workflow of Vue 3.0 is as follows:

  1. When defining a responsive object, Vue will convert it into a Proxy object.

  2. When accessing a property of a responsive object, Proxy will intercept the operation and return the corresponding property value.

  3. When modifying the properties of a responsive object, Proxy will intercept the operation and trigger the corresponding update operation.

  4. The update operation notifies the related components to re-render, thereby updating the view.

  5. How to use the Teleport component in Vue 3.0?

Answer: In Vue 3.0, you can use the Teleport component to render content anywhere in the DOM tree. Specifically, you can use elements in templates teleportand specify a target DOM element as the insertion point. For example:

<template>
  <div>
    <teleport to="#modal">
      <!-- 这里是插入的内容 -->
    </teleport>

    <div id="modal"></div>
  </div>
</template>

In the above example, the Teleport component will render its child elements into the DOM element with id "modal".

It should be noted that the Teleport component can only be used inside the same component tree, and the target element must exist in the DOM tree.

How to use the provide and inject API in Vue 3.0?

Answer: In Vue 3.0, you can use provideand injectAPI to realize the transfer of data from the parent component to the child component. Specifically, use a method in the parent component provideto provide a value, and a method in the child component injectto get that value. For example:

<template>
  <div>
    <child-component></child-component>
  </div>
</template>

<script>
export default {
  provide: {
    message: 'Hello, world!'
  }
}
</script>

In the example above, the parent component provideprovides a messagevalue named via a method. Then, use a method in the child component injectto get that value. For example:

<template>
  <div>{
   
   { message }}</div>
</template>

<script>
export default {
  inject: ['message']
}
</script>

In the above example, the child component injectgets messagethe value provided by the parent component through the method and renders it into the template.

How to use the defineAsyncComponent function in Vue 3.0?

In Vue 3.0, defineAsyncComponentfunctions can be used to define an asynchronous component. Specifically, this function can be used as componentthe value of the property of the component option to define an asynchronous component. For example:

import { defineAsyncComponent } from 'vue';

const MyAsyncComponent = defineAsyncComponent(() => {
  return import('./MyAsyncComponent.vue');
});

export default {
  components: {
    'my-async-component': MyAsyncComponent
  }
};

In the above example, we defineAsyncComponentdefined an asynchronous component through a function and registered it in componentsthe options of the parent component. This component can then be referenced using a tag in the template <my-async-component></my-async-component>.

How to use the watchEffect function in Vue 3.0?

Answer: In Vue 3.0, watchEffectfunctions can be used to monitor changes in responsive data. Specifically, functions can setupbe used in functions watchEffectto monitor responsive data, and when the responsive data changes, watchEffectthe function will be automatically re-executed. For example:

<template>
  <div>{
   
   { message }}</div>
</template>

<script>
import { defineComponent, reactive, watchEffect } from 'vue';

export default defineComponent({
  setup() {
    const state = reactive({
      message: 'Hello, world!'
    });

    watchEffect(() => {
      console.log(state.message);
    });

    return { state };
  }
});
</script>

In the above example, the property in watchEffectis monitored through the function . When the property changes, the function will automatically re-execute and print out the value.statemessagemessagewatchEffectmessage

What does the setup function in Vue 3.0 do? how it works

A: In Vue 3.0, writing component code using the Composition API requires defineComponentusing functions within functions setup. setupFunctions are a new component option that are used to define reactive data, computed properties, methods, etc. on components.

Specifically, setupthe function is executed when the component is created and returns an object containing defined reactive data, computed properties, methods, etc. This object can be used in templates.

For example:

<template>
  <div>{
   
   { count }}</div>
</template>

<script>
import { defineComponent, ref } from 'vue';

export default defineComponent({
  setup() {
    const count = ref(0);

    function increment() {
      count.value++;
    }

    return { count, increment };
  }
});
</script>

In the example above, setupthe function defines a countreactive data named and a incrementmethod named and puts them into an object to return. { { count }}Then, and can be used in the template @click="increment"to access the reactive data and call the defined method respectively.

How to use global configuration in Vue 3.0?

Answer: In Vue 3.0, you can use createAppthe second parameter of the function to set the global configuration. Specifically, an options object containing the global configuration can be created and createApppassed as the second argument to the function. For example:

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

const app = createApp(App, {
  // 全局配置
  config: {
    devtools: true,
    performance: true
  }
});

app.mount('#app');

In the above example, we defined an object containing devtoolstwo performanceglobal configuration items and createApppassed it as the second parameter of the function.

It should be noted that the priority of the global configuration is lower than that of the component option, so if the same configuration item is defined in the component option, the value of the component option will override the value of the global configuration.

How to use custom directives in Vue 3.0?

A: In Vue 3.0, you can directiveregister custom directives using methods. Specifically, you can register a custom directive by passing an object containing lifecycle functions such as beforeMount, mounted, beforeUpdate, updatedand , to the method. For example:unmounteddirective

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

const app = createApp(App);

app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});

app.mount('#app');

In the example above, we directiveregistered a focuscustom directive called via method and implemented mountedlifecycle functions in it to set focus on the element the directive is bound to.

Then, you can use the directive in the template v-focusto bind the custom directive. For example:

<template>
  <input v-focus>
</template>

How to use CSS scope in Vue 3.0?

A: In Vue 3.0, you can use <style scoped>tags to add scope to a component's style. Specifically, when we use a label in a component <style scoped>, the styles in the label will only be applied inside the current component, and will not affect other components or global styles.

For example:

<template>
  <div class="container">
    <h1>Hello, world!</h1>
  </div>
</template>

<style scoped>
.container {
  background-color: #f1f1f1;
  padding: 20px;
}

h1 {
  color: blue;
}
</style>

In the above example, we added scope to the component's styles. This means that .containerstyles will only be applied to elements inside the current component, and h1styles will only be applied to h1elements inside the current component.

It should be noted that <style scoped>when using tags, Vue will automatically add a unique hash value to each selector to achieve scope isolation.

How to use Teleport component in Vue 3.0?

Answer: In Vue 3.0, <teleport>components can be used to render content to a specified target location. Specifically, you need to use a tag in your template <teleport>and wrap the content you want to render inside that tag. The target location can be specified via toattributes or via <template v-slot:xxx>syntax. For example:

<template>
  <div>
    <button @click="showDialog = true">Show Dialog</button>

    <teleport to="body">
      <div v-if="showDialog" class="dialog">
        <h2>Dialog Title</h2>
        <p>This is the content of the dialog.</p>
      </div>
    </teleport>
  </div>
</template>

<style>
.dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  padding: 20px;
}
</style>

In the above example, we <teleport>wrapped an <div>element with a conditional judgment in the tag and specified the target location as body. When the condition is true, the <div>element is rendered into bodythe element.

How to pass data between components in Vue 3.0?

Answer: In Vue 3.0, data can be passed between components using methods such as props, $emitand .v-model

  • props: Pass data between parent and child components by passing the data as props to the child components. Specifically, use the attributes of the child component tag in the parent component to pass data, and use options in the child component propsto receive data. For example:
<!-- 父组件模板 -->
<template>
  <div>
    <child-component :message="message"></child-component>
  </div>
</template>

<!-- 子组件模板 -->
<template>
  <div>{
   
   { message }}</div>
</template>

<script>
export default {
  props: ['message']
}
</script>
  • $emit: Pass data between child and parent components by triggering a custom event in the child component and passing the data to the parent component as an event parameter. Specifically, use a method in the child component $emitto trigger an event, and use syntax in the parent component @xxxto listen to the event and process the data. For example:
<!-- 父组件模板 -->
<template>
  <div>
    <child-component @update-message="handleUpdateMessage"></child-component>
  </div>
</template>

<!-- 子组件模板 -->
<template>
  <button @click="updateMessage">Update Message</button>
</template>

<script>
import { defineEmits } from 'vue';

export default {
  emits: ['update-message'],
  
  methods: {
    updateMessage() {
      this.$emit('update-message', 'New message');
    }
  }
}
</script>
  • v-modelv-model: Two-way binding is conveniently implemented using the syntax in custom components . modelValueSpecifically, properties and events need to be used in child components update:modelValueto receive and send data, and syntax can be used in parent components v-modelfor two-way binding. For example:
<!-- 父组件模板 -->
<template>
  <div>
    <child-component v-model="message"></child-component>
  </div>
</template>

<!-- 子组件模板 -->
<template>
  <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</template>

<script>
import { defineEmits, defineProps } from 'vue';

export default {
  props: defineProps({
    modelValue: String
  }),

  emits: ['update:modelValue']
}
</script>

How to use Provide/Inject API in Vue 3.0?

Answer: In Vue 3.0, you can use provideand injectAPI to implement data transfer from ancestor components to descendant components. Specifically, you need to use methods in ancestor components that provide providedata to provide data, and options in descendant components that need to receive data injectto inject data. For example:

// 祖先组件
export default {
  data() {
    return {
      message: 'Hello, world!'
    }
  },

  provide() {
    return {
      getMessage: () => this.message
    }
  }
}

// 后代组件
export default {
  inject: ['getMessage'],

  mounted() {
    console.log(this.getMessage()); // 输出 'Hello, world!'
  }
}

In the above example, we used providea method in the ancestor component to provide the descendant component with a getMessagefunction named , which returned the ancestor component's messagedata. injectThen, use the option injection function in the descendant component getMessageand mountedcall the function in the hook function to get the data.

It should be noted that providethe and injectAPI are not reactive, so if the provided data changes, descendant components will not automatically update. If you need to perform reactive processing on the provided data, you can put the data into a reactive object (such as data or computed) and provide a method to get the data.

How to use Composition API in Vue 3.0?

Answer: In Vue 3.0, you can use the Composition API to organize and reuse component logic. Specifically, setupthe component instance context object (including properties such as props, data, methods, etc.) can be obtained through the function, and various responsive data and methods can be defined in it. For example:

import { ref, reactive, computed, watch } from 'vue';

export default {
  props: ['message'],

  setup(props) {
    // 定义响应式数据
    const count = ref(0);
    const user = reactive({
      name: 'Tom',
      age: 20
    });

    // 定义计算属性
    const doubleCount = computed(() => count.value * 2);

    // 定义方法
    function increment() {
      count.value++;
    }

    // 定义监听器
    watch(count, (newVal, oldVal) => {
      console.log(`count changed from ${oldVal} to ${newVal}`);
    });

    // 返回需要暴露给模板的数据和方法
    return {
      count,
      user,
      doubleCount,
      increment
    };
  }
};

In the above example, we setupdefined a reactive data count, a reactive object user, a computed property doubleCount, a method increment, and a listener inside the function. Then, these data and methods are exposed in the returned object, which can be used directly in the component's template.

Note that setupthe function must return an object whose properties will be exposed to the component's template. Also, the keyword cannot setupbe used inside a function thisbecause it refers to undefined. If you need to access the component instance context object, you can pass it in as setupa parameter of the function.

How to use provide/inject API to achieve cross-level component communication in Vue 3.0?

Answer: In Vue 3.0, you can use provideand injectAPI to achieve communication between cross-level components. Specifically, you need to use methods in ancestor components that provide providedata to provide data, and options in descendant components that need to receive data injectto inject data. For example:

// 祖先组件
export default {
  data() {
    return {
      message: 'Hello, world!'
    }
  },

  provide() {
    return {
      getMessage: () => this.message
    }
  }
}

// 子组件
export default {
  inject: ['getMessage'],

  mounted() {
    console.log(this.getMessage()); // 输出 'Hello, world!'
  }
}

// 后代组件
export default {
  inject: ['getMessage'],

  mounted() {
    console.log(this.getMessage()); // 输出 'Hello, world!'
  }
}

In the above example, we used providea method in the ancestor component to provide the descendant component with a getMessagefunction named , which returned the ancestor component's messagedata. injectThen, use the option injection function in the child component and the descendant component respectively getMessage, and mountedcall the function in the hook function to get the data.

It should be noted that providethe and injectAPI are not reactive, so if the provided data changes, descendant components will not automatically update. If you need to perform reactive processing on the provided data, you can put the data into a reactive object (such as data or computed) and provide a method to get the data.

Guess you like

Origin blog.csdn.net/weixin_54165147/article/details/129872968