12 ultra-detailed front-end Vue interview questions in 2023, including answer analysis. Everything you want is here! ! !

Welcome to Vue interviews in 2023. The following are 40 interview questions about Vue, each question comes with detailed answers and code explanations.

  1. Please explain what Vue.js is. What are its core functions?
    Vue.js is a popular JavaScript front-end framework for building user interfaces. Its core function is to achieve declarative rendering, component-based development and responsive data binding by encapsulating the core library and plug-in ecosystem.

  2. Please explain Vue’s two-way data binding principle.
    Vue’s two-way data binding is implemented through Vue’s responsive system. When the data changes, Vue will automatically recognize the change and synchronize the changed data to the view. At the same time, when the user interacts with the view, Vue can also dynamically reflect the user's input to the data.

Code explanation

The text you entered is: { { message }}

In the above example, we implemented two-way data binding using the v-model directive. The value of the element is automatically two-way bound to the message data attribute, and any changes to the message data will be synchronized to the input box, and vice versa.

  1. What is a Vue component? How to define a Vue component?
    In Vue, components are reusable Vue instances. It encapsulates its own templates, data, methods, styles, etc., and can be used multiple times in the application.

A Vue component can be defined through the Vue.component method.

Code explanation

<template id="hello-template">
  <div>
    <h2>Hello {
    
    {
    
     name }}!</h2>
    <button @click="greet">Greet</button>
  </div>
</template>

<script>
Vue.component('hello', {
    
    
  template: '#hello-template',
  data() {
    
    
    return {
    
    
      name: 'Vue'
    }
  },
  methods: {
    
    
    greet() {
    
    
      alert('Hello!')
    }
  }
})
</script>

In the above example, we defined a Vue component named Hello. The component's template is defined through an external element, using its content as the component's template. This component also defines a name data attribute and a greet method, which can be used in templates.

  1. How to perform conditional rendering in Vue?
    In Vue, we can use the v-if and v-show instructions to implement conditional rendering.

v-if will dynamically add or delete elements based on the true or false expression, while v-show only controls the display and hiding of elements.

Code explanation

<div id="app">
  <button @click="toggle">Toggle</button>
  <p v-if="visible">这是一个可见的段落。</p>
  <p v-show="visible">这是另一个可见的段落。</p>
</div>

<script>
new Vue({
    
    
  el: '#app',
  data: {
    
    
    visible: true
  },
  methods: {
    
    
    toggle() {
    
    
      this.visible = !this.visible
    }
  }
})
</script>

In the above example, we use the v-if and v-show directives to control the visibility of two paragraph elements based on the true or false value of the visible data attribute. After clicking the button, the value of visible will be inverted, triggering conditional rendering.

  1. How to handle user input and events in Vue?
    In Vue, we can use the v-on directive (abbreviated as @) to listen to DOM events and custom events.

Code explanation

<div id="app">
  <button @click="handleClick">点击我</button>
  <input @input="handleInput" placeholder="输入一些文字">
  <p>{
    
    {
    
     message }}</p>
</div>

<script>
new Vue({
    
    
  el: '#app',
  data: {
    
    
    message: ''
  },
  methods: {
    
    
    handleClick() {
    
    
      alert('按钮被点击!')
    },
    handleInput(event) {
    
    
      this.message = event.target.value
    }
  }
})
</script>

In the above example, we use the @click directive to listen to the click event of the button and pop up a prompt box in the handleClick method. In addition, we also use the @input directive to listen to the input event of the input box and update the message data in the handleInput method.

  1. How to handle asynchronous requests in Vue?
    In Vue, we can use third-party libraries such as vue-resource or axios to handle asynchronous requests. These libraries encapsulate XHR requests and provide simpler APIs for sending GET, POST and other requests.

Code explanation

<div id="app">
  <button @click="fetchData">获取数据</button>
  <ul>
    <li v-for="item in items" :key="item.id">{
    
    {
    
     item.name }}</li>
  </ul>
</div>

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script>
new Vue({
    
    
  el: '#app',
  data: {
    
    
    items: []
  },
  methods: {
    
    
    fetchData() {
    
    
      // 使用vue-resource发送GET请求
      this.$http.get('/api/data')
        .then(response => {
    
    
          this.items = response.data
        })
        .catch(error => {
    
    
          console.error(error)
        })
    }
  }
})
</script>

In the above example, we use the vue-resource library to send a GET request and assign the returned data to the items array after the request is successful. In this way, we can use the v-for directive in the template to render the data list.

  1. Please explain the life cycle hook function in Vue.
    In the life cycle of a Vue instance, there are some specific stages, such as creation, update and destruction. Vue provides some lifecycle hook functions that allow us to add custom code at these specific stages.

Commonly used life cycle hook functions include: beforeCreate, created, mounted, updated, destroyed, etc.

Code explanation

<div id="app">
  <p>{
    
    {
    
     message }}</p>
</div>

<script>
new Vue({
    
    
  el: '#app',
  data: {
    
    
    message: 'Hello, Vue!'
  },
  beforeCreate() {
    
    
    console.log('beforeCreate')
  },
  created() {
    
    
    console.log('created')
  },
  mounted() {
    
    
    console.log('mounted')
  },
  updated() {
    
    
    console.log('updated')
  },
  destroyed() {
    
    
    console.log('destroyed')
  }
})
</script>

In the above example, we print to the console to show the order in which each lifecycle hook function is called. You can view the output in your browser's developer tools.

  1. What is the difference between computed and watch in Vue?
    Both computed and watch are used to monitor changes in data, but they have some differences.

computed is cached based on its dependencies, and will only be recalculated when the dependent data changes, rather than recalculated every time it is accessed.

Watch observes a specific data and executes a callback function when the data changes. It is more suitable for processing a data change that requires asynchronous or expensive operations.

Code explanation

<div id="app">
  <input v-model="message" placeholder="输入一些文字">
  <p>你输入的文字是:{
    
    {
    
     message }}</p>
  <p>计算属性:{
    
    {
    
     reversedMessage }}</p>
</div>

<script>
new Vue({
    
    
  el: '#app',
  data: {
    
    
    message: ''
  },
  computed: {
    
    
    reversedMessage() {
    
    
      return this.message.split('').reverse().join('')
    }
  },
  watch: {
    
    
    message(newValue, oldValue) {
    
    
      console.log(`message 发生变化:${
      
      oldValue}${
      
      newValue}`)
    }
  }
})
</script>

In the above example, we defined a calculated property reversedMessage, which is used to reverse the content of the message. When the user enters text, the message will change and reversedMessage will be recalculated and displayed. At the same time, we use watch to observe changes in message and print out the changed value.

  1. What is routing in Vue? How to configure routing?
    In Vue, routing is used to build single-page applications. It allows us to load different components according to different URL paths to achieve switching and navigation within the page.

To configure routing, we need to introduce the vue-router library and define a set of routing rules based on page requirements.

Code explanation

<div id="app">
  <router-link to="/home">主页</router-link>
  <router-link to="/about">关于</router-link>
  <router-view></router-view>
</div>

<script>
const Home = {
    
     template: '<div>这是主页</div>' }
const About = {
    
     template: '<div>这是关于页面</div>' }

const routes = [
  {
    
     path: '/home', component: Home },
  {
    
     path: '/about', component: About }
]

const router = new VueRouter({
    
    
  routes
})

new Vue({
    
    
  el: '#app',
  router
})
</script>

In the above example, we created two navigation links through tags, pointing to the home page and about page. Use labels to display currently active components.

  1. How to manage state in Vue?
    In Vue, we can use vuex for state management. Vuex is Vue's official state management library, which provides centralized storage and management of various application states to facilitate communication and data sharing between different components.

Code explanation

<div id="app">
  <p>计数器:{
    
    {
    
     count }}</p>
  <button @click="increment">增加</button>
</div>

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex"></script>
<script>
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0
  },
  mutations: {
    
    
    increment(state) {
    
    
      state.count++
    }
  }
})

new Vue({
    
    
  el: '#app',
  store,
  computed: {
    
    
    count() {
    
    
      return this.$store.state.count
    }
  },
  methods: {
    
    
    increment() {
    
    
      this.$store.commit('increment')
    }
  }
})
</script>

In the above example, we created a simple counter and used vuex for state management. We get the status through this. s t o r e . s t a t e , and get the status through ` t h i s . store.state , and through `this. store.s tateReceipt letter, notification 'this. store.commit` next submission change.

  1. Please explain what dynamic components in Vue are.
    Dynamic components are a special type of components in Vue. It allows us to dynamically switch between different components based on different data or states.

When using dynamic components, we specify the component to render through the element and is attributes.

Code explanation

<div id="app">
  <button @click="toggle">切换组件</button>
  <component :is="currentComponent"></component>
</div>

<script>
const ComponentA = {
    
     template: '<div>组件A</div>' }
const ComponentB = {
    
     template: '<div>组件B</div>' }

new Vue({
    
    
  el: '#app',
  data: {
    
    
    currentComponent: 'ComponentA'
  },
  methods: {
    
    
    toggle() {
    
    
      this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'
    }
  },
  components: {
    
    
    ComponentA,
    ComponentB
  }
})
</script>

In the above example, we switch the display of ComponentA and ComponentB components by clicking the button. Clicking the button will trigger the toggle method, which dynamically changes the value of currentComponent.

  1. How to implement the transition effect in Vue?
    In Vue, we can achieve animated transition effects through the transition element and CSS transition class.

Code explanation

<div id="app">
  <button @click="toggle">切换</button>
  <transition name="fade">
    <p v-if="visible">这是一个带有过渡效果的段落。</p>
  </transition>
</div>

<style>
.fade-enter-active, .fade-leave-active {
    
    
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
    
    
  opacity: 0;
}
</style>

<script>
new Vue({
    
    
  el: '#app',
  data: {
    
    
    visible: false
  },
  methods: {
    
    
    toggle() {
    
    
      this.visible = !this.visible
    }
  }
})
</script>

In the above example, we wrap the element to be transitioned with an element and add a name attribute to specify the name of the transition effect. By specifying the four CSS classes fade-enter-active, fade-leave-active, fade-enter and fade-leave-to, we define a gradient transition effect.

Guess you like

Origin blog.csdn.net/qq_27244301/article/details/133036821