Vue3 combined api single file component writing method

Vue3 combined api single-file component writing method

This blog post will give an in-depth introduction to Vue3's combined API and how to write single-file components. We'll start by installing and configuring Vue3, and then show step-by-step details on how to create a simple single-file component. Beyond that, we'll discuss common patterns and techniques for working with composite APIs, such as reactive state management, alternatives to lifecycle hooks, custom composite APIs, reactive processing and listening of data, and components communication etc.

1 Basic principles and concepts of Vue3 combined API

1.1 Composition API in Vue3

The Composition API in Vue3 is a new way of writing component logic, which provides better code organization, type inference, testing support and reusability. Compared with Vue2's Options API, Composition API is more flexible and extensible.

In the Composition API, we use the setup function to define the logical part of the component. The setup function is a special function that is called before creating a component instance and receives two parameters: props and context. props is a collection of attributes passed into the component, and context contains some methods and data associated with the component.

1.2 Comparison with Vue2 Options API

Compared with Vue2's Options API, Composition API has the following advantages:

  • Better code organization: By putting related logic inside the same function, you can organize your code more clearly.
  • Type inference: Since the setup function is a normal JavaScript function, it is easier to get support for type inference.
  • Testing support: Since the logic is encapsulated in a separate function, unit testing can be done more conveniently.
  • Reusability: Logic can be abstracted into custom Hooks and reused in multiple components.

1.3 Why choose to use the composition API

Using a composition API provides the following benefits:

  • Better code organization: Putting related logic inside the same function makes the code easier to understand and maintain.
  • Better type deduction: Since the setup function is an ordinary JavaScript function, better type deduction support can be obtained to reduce errors.
  • Better testing support: logic is encapsulated in independent functions, which can be more convenient for unit testing.
  • Higher reusability: Logic can be abstracted into custom Hooks and reused in multiple components.

Using a combined API can provide a better development experience and code quality, making the development of Vue3 more flexible and scalable.

2 Install and configure Vue3

In order to install and configure Vue3, you need to follow these steps:

2.1 Introducing the latest version of Vue3

First, you need to include the latest version of Vue3 in your project. Vue3 can be installed by using npm or yarn.

If using npm, run the following command:

npm install vue@next

If using yarn, run the following command:

yarn add vue@next

This will install Vue3 and its associated dependencies.

2.2 Basic configuration for creating a Vue application

Once you have Vue3 installed, you can start creating the basic configuration of your Vue application.

Create a new file in your project, for example main.js, and add the following code:

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

createApp(App).mount('#app');

The above code imports createAppthe function and the root component App, then calls createAppthe function to create a Vue application instance, passing it the root component. Finally, use mountthe method to mount the Vue application on an element on the HTML page (assuming an appelement with id here).

Next, create a file in your project called App.vue, and add the following code as a template for the root component:

<template>
  <div id="app">
    <!-- Your application content here -->
  </div>
</template>

<script>
export default {
      
      
  // Your component options here
}
</script>

<style>
/* Your component styles here */
</style>

In the above code, you can place the content of the application <div id="app">inside the element.

3 Create a simple single-file component

3.1 Create a .vue file

First, create a new file in your project .vue, eg MyComponent.vue.

3.2 Writing component templates

In MyComponent.vuethe file, write the template for the component. The template section defines the structure and layout of the component. Here is an example:

<template>
  <div>
    <h1>{
   
   { message }}</h1>
    <button @click="increment">Increment</button>
  </div>
</template>

The above code shows a simple component with a title and a button. The title is bound to a variable using double curly brace interpolation message, and the button @clickis bound to incrementa method using a directive.

3.3 Implement the combined API logic of components

3.3.1 Refactoring the original code

Next, you need to refactor the original logic into a composite API form. In MyComponent.vuethe file, add the following code:

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

export default {
    
    
  setup() {
    
    
    const message = ref('Hello, Vue!');
    
    function increment() {
    
    
      message.value += '!';
    }
    
    return {
    
    
      message,
      increment
    };
  }
}
</script>

The above code uses setupfunctions to implement the logic of the composition API. Inside setupthe function, we refcreated a reactive data using the function messageand defined a incrementmethod named .

Finally, returnthe data and methods that need to be used in the template are exported through the statement.

3.3.2 Creating and exporting reusable logic functions

If you want to extract some logic code into reusable functions, you can create and export them. For example, add the following code to the same file:

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

function useCounter() {
    
    
  const count = ref(0);

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

  return {
    
    
    count,
    increment
  };
}

export default {
    
    
  setup() {
    
    
    const {
    
     count, increment } = useCounter();

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

The preceding code creates a useCounterreusable logic function named , which returns an object containing the counter value and a method to increment the counter.

Then, setupinside the function, we call useCounterthe function, and destructure its return value into countsum incrementvariables.

Finally, returnthese variables are exported for use by the template via a statement.

3.4 Using components in your application

To use components in a Vue3 application, you need to follow these steps:

  1. Create a component: First, create a .vue file to define your component. This file contains templates, styles, and logic code. For example, create a file called "HelloWorld.vue".
<template>
  <div>
    <h1>{
   
   { greeting }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      greeting: 'Hello, World!'
    }
  }
}
</script>

<style scoped>
h1 {
  color: blue;
}
</style>
  1. Import and register components: In your main application file (usually main.js), import and register your components globally.
import {
    
     createApp } from 'vue'
import HelloWorld from './components/HelloWorld.vue'

const app = createApp()
app.component('hello-world', HelloWorld)
app.mount('#app')
  1. Using components in your application: You can now use your components in your application's templates. Just add the component name to the template as a custom element.
<div id="app">
  <hello-world></hello-world>
</div>

This way, your component is visible in the application and its data and logic live.

Note that in the above examples, we have written the components as single-file components. This is the way Vue recommends. It encapsulates the template, style and logic of the component in one file, making the code more modular and maintainable.

4 Common patterns and techniques for using the Vue3 Composition API

When working with Vue3's composition API, there are some common patterns and techniques that can help you better organize and manage your code.

4.1 Responsive state management

In Vue3, you can use refand reactivefunctions to create reactive state. refis used to create a reactive reference of a single value, whereas reactiveit is used to create a reactive object containing multiple properties.

import {
    
     ref, reactive } from 'vue'

// 创建一个响应式引用
const count = ref(0)

// 创建一个响应式对象
const state = reactive({
    
    
  message: 'Hello',
  name: 'World'
})

You can then use these reactive states in your components:

export default {
    
    
  setup() {
    
    
    // 使用响应式引用
    const counter = ref(0)
    
    // 使用响应式对象
    const data = reactive({
    
    
      message: 'Hello',
      name: 'World'
    })

    return {
    
    
      counter,
      data
    }
  }
}

Note that when using reactive state, you need to use .valueto access refdata of type:

<template>
  <div>
    <p>Counter: {
   
   { counter }}</p>
    <p>Message: {
   
   { data.message }}</p>
    <p>Name: {
   
   { data.name }}</p>
  </div>
</template>

<script>
export default {
      
      
  setup() {
      
      
    const counter = ref(0)
    const data = reactive({
      
      
      message: 'Hello',
      name: 'World'
    })

    return {
      
      
      counter,
      data
    }
  }
}
</script>

4.2 Alternatives to life cycle hook functions

In Vue3, lifecycle hooks are replaced by setupfunctions. You can setupperform the logic of component initialization in the function and return the data and methods to be exposed to the template.

export default {
    
    
  setup() {
    
    
    // 组件初始化逻辑
    
    return {
    
    
      // 要暴露给模板的数据和方法
    }
  }
}

If you need to perform some operations after the component is mounted or before it is unmounted, you can use onMountedand onUnmountedhook functions:

import {
    
     onMounted, onUnmounted } from 'vue'

export default {
    
    
  setup() {
    
    
    onMounted(() => {
    
    
      // 组件挂载后执行的操作
    })

    onUnmounted(() => {
    
    
      // 组件卸载前执行的操作
    })

    return {
    
    }
  }
}

4.3 Custom composite APIs for specific functions

In addition to using the built-in composition API provided by Vue, you can also create your own custom composition API to encapsulate the logic of specific functions.

For example, suppose you want to create a reusable timer logic, you can write a custom composite API called "useTimer":

import {
    
     ref, watch, onUnmounted } from 'vue'

export function useTimer(initialValue = 0) {
    
    
  const timer = ref(initialValue)

  const startTimer = () => {
    
    
    timer.value = 0
    const interval = setInterval(() => {
    
    
      timer.value++
    }, 1000)
    onUnmounted(() => {
    
    
      clearInterval(interval)
    })
  }

  watch(timer, (newValue) => {
    
    
    console.log('Timer:', newValue)
  })

  return {
    
    
    timer,
    startTimer
  }
}

Then, use the custom composition API in your component:

import {
    
     useTimer } from './useTimer'

export default {
    
    
  setup() {
    
    
    const {
    
     timer, startTimer } = useTimer()

    return {
    
    
      timer,
      startTimer
    }
  }
}

This way, you can reuse timer logic in multiple components.

4.4 Use ref and reactive for data responsive processing

In Vue3, we can use refand reactivefunctions to create reactive references and objects.

  • Use reffunctions to create reactive refs:
import {
    
     ref } from 'vue'

const count = ref(0)
console.log(count.value) // 输出:0

count.value++ // 修改值
console.log(count.value) // 输出:1
  • Use reactivefunctions to create reactive objects:
import {
    
     reactive } from 'vue'

const state = reactive({
    
    
  count: 0,
  name: 'John'
})

console.log(state.count) // 输出:0
console.log(state.name) // 输出:'John'

state.count++ // 修改值
console.log(state.count) // 输出:1

4.5 Use watchEffect and watch for data monitoring

Vue3 provides watchEffectand watchfunctions for data listening.

  • Use to watchEffectmonitor changes in the responsive state and execute the callback function:
import {
    
     watchEffect, reactive } from 'vue'

const state = reactive({
    
    
  count: 0
})

watchEffect(() => {
    
    
  console.log('Count changed:', state.count)
})
  • Use watchfunctions to listen for specific reactive states and execute callback functions:
import {
    
     watch, reactive } from 'vue'

const state = reactive({
    
    
  count: 0
})

watch(
  () => state.count,
  (newVal, oldVal) => {
    
    
    console.log('Count changed:', newVal, oldVal)
  }
)

4.6 Use offer and inject to realize communication between components

In Vue3, we can use provideand injectto achieve communication between components.

  • provideUse provided data in parent component :
import {
    
     provide, reactive } from 'vue'

const state = reactive({
    
    
  count: 0
})

provide('state', state)
  • Use in child components injectto get the provided data:
import {
    
     inject } from 'vue'

export default {
    
    
  setup() {
    
    
    const state = inject('state')
    console.log(state.count) // 输出:0

    return {
    
    }
  }
}

With these tips, you can take better advantage of Vue3's compositional API to handle data responsiveness, data listening, and communication between components.

5 summary

Vue3's combined API and single-file components bring us a more flexible and maintainable development method. Through the composition API, we can better organize the logic of components, and can easily reuse and share code logic. The single-file component integrates the template, style and logic in one file, which simplifies the development process and improves the readability and maintainability of the code.

In this article, we've covered how to build an application using Vue3's compositional API and single-file components from start to finish. We learned how to install and configure Vue3, and explained in detail the steps to create single-file components. Additionally, we explore some common compositional API patterns and techniques, such as reactive state management, alternatives to lifecycle hooks, and communication between components.

By learning and practicing these concepts and techniques in depth, you can advance your skills in Vue development. Whether you are a novice or an experienced developer, Vue3's composite API and single-file components will bring you a better development experience and higher efficiency.

In the future, the development of Vue3 will bring more new features and functions. We encourage you to stay tuned to the Vue ecosystem and continue to learn and explore further. Thank you for reading this article, I hope this article will help you learn and practice Vue3 combined API and single-file components. Best of luck with your Vue development!

Supongo que te gusta

Origin blog.csdn.net/weixin_55756734/article/details/132332650
Recomendado
Clasificación