search
HomeWeb Front-endJS TutorialSummary of Vue component implementation tips

Summary of Vue component implementation tips

Dec 28, 2017 pm 01:46 PM
accomplishSummarize

This article mainly introduces a summary of tips for implementing Vue components in detail. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Component, as the name suggests, is to abstract a relatively independent function that will be used multiple times into a component! If we want to abstract a certain function into a component, we need to make this component a black box for others. They don't need to care about how it is implemented, they only need to call it according to the agreed interface!

I used a picture to briefly summarize the composition of components in Vue:

You can see that there are quite a lot of things included in the components, and , there are still many points not listed, and each knowledge point here can be expanded and discussed a lot. However, we are not talking about principles here, only usage.

We take a tips pop-up window as an example to comprehensively apply the knowledge points of the following components. tips pop-up window, almost all frameworks or class libraries will have a pop-up window component, because the pop-up window function is usually very common, and the module is highly decoupled!

1. Interface convention

The pop-up window we implement here can use the following knowledge points: props, event, slot, ref, etc. Here we can also see how each knowledge point is used.


/**
 * modal 模态接口参数
 * @param {string} modal.title 模态框标题
 * @param {string} modal.text 模态框内容
 * @param {boolean} modal.showbtn 是否显示按钮
 * @param {string} modal.btnText 按钮文字
 */

 Vue.component('tips', {
  props : ['tipsOptions'],
  template : '#tips',

  data(){
    return{
      show : false
    }
  },

  computed:{
    tips : {
      get() {
        let tips = this.tipsOptions || {};
        tips = {
          title: tips.title || '提示',
          text: tips.text || '',
          showbtn : tips.showbtn || true,
          btnText : tips.btnText || '确定'
        };
        // console.log(tips);
        return tips;
      }
    }
  }
})

2. Implementation of modal component

tips component is relatively simple to implement and is only used for A simple pop-up layer that prompts the user.

Template:


<p class="tips" v-show="show" transition="fade">
  <p class="tips-close" @click="closeTips">x</p>
  <p class="tips-header">
    <slot name="header">
      <p class="title">{{tips.title}}</p>
    </slot>
  </p>
  <p class="tips-body">
    <slot name="body">
      <p class="notice">{{tips.text}}</p>
    </slot>
  </p>
  <p class="tips-footer">
    <a href="javascript:;" rel="external nofollow" rel="external nofollow" v-if="tips.showbtn" @click="yes" >{{tips.btnText}}</a>
  </p>
</p>

The template structure is divided into three parts, title, content and operation area. Here you can either use props to pass strings or use slots for customization.

tips style:


.tips {
  position: fixed;
  left: 10px;
  bottom: 10px;
  z-index: 1001;
  -webkit-overflow-scrolling: touch;
  max-width: 690px;
  width: 260px;
  padding: 10px;
  background: #fff;
  box-shadow: 0 0 10px #888;
  border-radius: 4px;
}
.tips-close{
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
}
.tips-header{
  text-align: center;
  font-size: 25px;
}

Methods within the component:


methods:{
  closeTips(){
    this.show = false;
  },

  yes : function(){
    this.show = false;
    this.$emit(&#39;yes&#39;, {name:&#39;wenzi&#39;, age:36}); // 触发yes事件
  },

  showTips(){
    var self = this;
    self.show = true;

    setTimeout(function(){
      // self.show = false;
    }, 2000)
  }
}

3 . Call the tips component

First we start rendering the component:


<p class="app">
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" @click="showtips">显示</a>
  <tips :tips-options="tipsOptions" ref="dialog" @yes="yes" v-cloak >
    <h3 id="提示标题">提示标题</h3>
    <p slot="body">
      <p>hello world</p>
      <p>wenzi</p>
    </p>
  </tips>
</p>

Click the display button to display tips:


var app = new Vue({
  el : &#39;.app&#39;,

  data : {
    tipsOptions : {
      title : &#39;tip&#39;
    }
  }

  methods:{
    // 监听从组件内传递出来的事件
    yes(args){
      // console.log( args );
      alert( JSON.stringify(args) );
    },

    // 显示tips
    showtips(){
      // console.log( this.$refs );
      this.$refs.dialog.showTips();
    }
  }
})

4. Summary

In this simple tips component, we implement using props to pass parameters and $emit to outwards Pass parameters and use slots to customize content.

It should be noted that component props are one-way binding, that is, when the properties of the parent component change, the child component can receive the corresponding data changes, but in turn an error will occur. That is, the data passed by props cannot be modified in the child component to achieve the purpose of modifying the properties of the parent component. This is to prevent child components from accidentally modifying the state of the parent component.

In addition, every time the parent component is updated, all props of the child component will be updated to the latest values. This means you should not change props inside child components. If you do this, Vue will warn you in the console. If you really need to make changes in the subcomponent, you can use these two methods:

Define a local variable and initialize it with the value of prop:


props: [&#39;initialCounter&#39;],
data: function () {
 return { counter: this.initialCounter }
}

Define a calculated property, process the value of prop and return it.


props: [&#39;size&#39;],
computed: {
 normalizedSize: function () {
  return this.size.trim().toLowerCase()
 }
}

Of course, this is just the implementation of components in a single page. We will also implement more complex components in the future.

Related recommendations:

Summary of tips in PHP development

css related tips

python tips

The above is the detailed content of Summary of Vue component implementation tips. 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
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool