Home  >  Article  >  Web Front-end  >  VUE3 Getting Started Tutorial: Using the Vue.js plug-in to encapsulate the star rating component

VUE3 Getting Started Tutorial: Using the Vue.js plug-in to encapsulate the star rating component

WBOY
WBOYOriginal
2023-06-16 08:23:311839browse

In web applications, star rating components are often used to rate goods, services or other content. In order to make it easier for developers to use, the Vue.js community already has many star rating component plug-ins. However, it is also necessary to encapsulate a star rating component plug-in yourself. This article will abandon the traditional way of writing components, introduce the Composition API of Vue.js 3, and explain how to use the Vue.js plug-in to encapsulate a star rating component.

Let’s first learn about the Composition API. The Composition API mainly has the following advantages:

  1. Better logic encapsulation: Now, logic can be grouped according to logic instead of defining properties and methods according to the life cycle or options API. In addition, you can group them according to the single responsibility principle, making the code easier to maintain and test.
  2. Easier to reuse logic: Encapsulating logic into custom hooks makes it easy to share and reuse within components, share it with other developers, or even distribute it on npm for others to use people use.
  3. More intuitive component code: Because the logic is split into smaller chunks, the code is made more intuitive and easier to understand, reducing unnecessary markup and nesting, making it easier to deduce the role of the component.
  4. Better type inference: The Composition API is tightly integrated with TypeScript, allowing developers to take advantage of TypeScript’s type inference capabilities to write more robust code.

Next, we use the Composition API to design and implement the star rating component.

Step 1: Create a Vue.js plug-in

Plug-ins are an extension of the underlying structure of Vue.js. Vue.js plugins can provide global-level functionality to Vue.js applications, so they are suitable for implementing common components or directives. The following are the basic steps to create and install a Vue.js plugin:

  1. Create a JavaScript object and define the install method in the object. This method receives Vue as a parameter and registers new components or other functions within the scope of a new Vue() instance.
  2. Define components or other utilities in the install method.
  3. Call the static use() method on Vue and pass an object containing the plug-in that needs to be installed. Vue.js will call the install method in this object, passing the Vue.js instance as a parameter to the method.

The sample code is as follows:

// 定义插件对象
const StarRating = {
  install: function(Vue) {
    // 在install方法中注册全局组件 star-rating
    Vue.component('star-rating', {
      // 组件选项
    })
  }
}

// 调用Vue.use()方法安装插件
Vue.use(StarRating)

Step 2: Design the properties and events of the component

In the Composition API, it is recommended to use the reactive() method to define components state. Use the computed() method to calculate the derived state of the component, and use the watch() method to monitor the component's state changes. To better pass data through props and emit, we can use reactive() to define property and event objects.

The component should have the following attributes:

  • rating: current rating
  • maxRating: maximum number of ratings
  • starSize: star size
  • padding: the spacing between stars
  • showRating: whether to display the rating

The component should have the following events:

  • update : Automatically triggered when the rating is updated

The following is the sample code to define the properties and event objects:

const StarRating = {
  install: function(Vue) {
    Vue.component('star-rating', {
      setup(props, {emit}) {
        const state = reactive({
          rating: 0,
          maxRating: props.maxRating || 5,
          starSize: props.starSize || 25,
          padding: props.padding || 5,
          showRating: props.showRating || false,
        })

        function updateRating(rating) {
          state.rating = rating
          emit('update', rating)
        }

        return {
          state,
          updateRating
        }
      }
    })
  }
}

Step 3: Implement the component UI

Next, We use template code to implement the UI of the component. The setup() function is used in Vue.js3 to set component status and events, and interpolation expressions and instructions in template are used to render component UI.

The following is a sample code to implement the component UI:

const StarRating = {
  install: function(Vue) {
    Vue.component('star-rating', {
      setup(props, {emit}) {
        const state = reactive({
          rating: 0,
          maxRating: props.maxRating || 5,
          starSize: props.starSize || 25,
          padding: props.padding || 5,
          showRating: props.showRating || false,
        })

        function updateRating(rating) {
          state.rating = rating
          emit('update', rating)
        }

        const stars = []
        for (let i = 0; i < state.maxRating; i++) {
          stars.push(i < state.rating ? 'star' : 'star_border')
        }

        return {
          state,
          updateRating,
          stars,
        }
      },
      template: `
        <div>
          <i 
            v-for="star in stars"
            :key="star"
            :class="[star]"
            :style="{
              'font-size': state.starSize + 'px', 
              'padding-right': state.padding + 'px',
            }"
            @click="updateRating(stars.indexOf(star) + 1)"
          ></i>
          <span v-if="state.showRating">{{state.rating}}/{{state.maxRating}}</span>
        </div>
      `
    })
  }
}

We used the v-for directive to loop through rendering stars, and used i tags and FontAwesome font icons to render star icons. This way we can update the ratings based on the user's choices.

Step 4: Using the Component

Now, we have completed the development of a star rating component plug-in. We can install this plugin globally in our Vue.js application and then use it in any component template.

Sample code for using components in Vue.js application:

const app = Vue.createApp({})
app.use(StarRating)

app.component('my-component', {
  data() {
    return {
      rating: 3
    }
  },
  template: `
    <div>
      <star-rating 
        :max-rating="5" 
        :show-rating="true"
        :rating="rating"
        @update="rating = $event"
      />
    </div>
  `
})

app.mount('#app')

In this sample code, we registered the StarRating plugin in the Vue.js application and added it in my-component The scoring component is used in the component. In the my-component component, we use the $event parameter to access the new rating value of the update event.

Conclusion

The Composition API brings many new features to Vue.js component development. Using these new features combined with the Vue.js plug-in mechanism makes it easier to encapsulate and reuse components. In this article, we learned step by step how to develop a star rating component using the Composition API and the Vue.js plugin. Now, you can use these techniques to develop and package your own component plug-ins.

The above is the detailed content of VUE3 Getting Started Tutorial: Using the Vue.js plug-in to encapsulate the star rating component. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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