• Opening: a brief introduction and demonstration of vue.js
  • The essence of VUE development – components
  • Three apis of the VUE component are prop, Event, and Slot
  • How components communicate
  • Example: Baht Baoyi help center front-end components

Opening: a brief introduction and demonstration of vue.js

Vue was released in 2013. It is an incremental framework, but also a lightweight framework. It only cares about data, so that developers do not have to pay too much attention to the DOM change and operation

DOM: Document Object Model (DOM) is a generic programming interface for manipulating HTML or XML, which is not described here

Two-way binding code demonstration
// html
<body>
    <div id="app">
        <input type="text" v-model="note">
        <p>{{ note }}</p>
    </div>
</body>

// js
var app = new Vue({
    el: '#app',
    data: {
        note: ' '}})Copy the code

Compared to other Web front-end frameworks, VUE is easier to get started, the code and API are more concise and intuitive, and faster!

The essence of VUE development – components

The essence of VUE is its components and componentization. Writing a VUE project is actually writing components one by one.

Classification of VUE Components (three categories)
  1. Each page == generated by ==vue-router is also a component (.vue) in essence. It mainly hosts the HTML structure of the current page and includes routine services such as data acquisition, data sorting, and data visualization. The entire file is relatively large because it is a rendering of the route and will not be reused and therefore will not provide an interface to the outside world. In project development, most of the code we write is this kind of components (pages), when co-development, each person maintains their own page, rarely intersection. This type of component is relatively the best to write, because it is mainly to restore the design draft, complete the requirements, do not require much module and architecture design considerations;
  2. Non-business, independent, functional-specific == base components ==, such as date pickers, modal boxes, etc. As the basic control of the project, this kind of component will be widely used. Therefore, the API of the component is highly abstracted, and different functions can be realized through different configurations.
  3. == Service component ==. Unlike the second type of independent components, it only contains a certain function, but is reused by multiple pages in the business. The difference between it and independent components is that business components are only used in the current project, not universal, and will contain some business, such as data requests; Independent components do not contain business, can be used in any project, a single function, such as an input box with custom data validation function.

Three apis of the VUE component are prop, Event, and Slot

A component is complex or not, are composed of three parts, ==prop (property) ==, ==event (event) ==, ==slot (slot) ==, must first design these three parts, can continue to develop the component, otherwise, once the code is released, it is very difficult to modify the API, the maintenance of the component is to add new functions. Rather than constantly changing the interface;

Prop (properties)

Prop defines the configurable properties of the component and determines the core functionality of the component. When writing a generic component, it’s better to write props as an object. This way, you can set the type, default value, or custom validating property for each property. This is important in component development, but many people ignore it.

For example: print pop-up components at the cashier (part of the code is abbreviated)

<template> <! -- print --> <el-dialog :show-close="false"
    :visible="visiable"
    :closeOnClickModal="false"
    custom-class="zbe-dialog chose-sale"
    width="1000px"
    center
  >
    <p slot="title" class="zbe-dialog-title"</p> <div class="box">
      <el-row style="margin-top:10px">
        <el-col :span="24" v-if=! "" web_view_error" v-loading="loading"> <! -- Preview window --> < webView ref="view"
            id="view"
            :src="visiable? data_web_view_url:' '"
            autosize
            plugins
            disablewebsecurity
            allowpopups
            style="display:inline-flex; width:100%; height:400px;"></webview> </el-col> <! -> < span style = "box-sizing: border-box; color: RGB (93, 93, 93)"24" v-if="web_view_error&&! loading"> Print load failed </el-col> </el-row> <! -- Close button --> <el-row> <el-col :span="11" :offset="20" style="margin-top:20px">
          <el-button @click="doCancle"> close < / el - button > < / el - col > < / el - row > < / div > < / el - dialog > < / template > < script >export default {
  name: "print", props: {// props for hiding the component show: {type: Boolean,
      default: false}, // print the URL web_view_URL:""// Turn off web_view_reback_path after printing:""Web_view_error:false
  },
  data() {
    return {
      visiable: false,
      domReady: true,
      data_web_view_url: "/",
      loading: false}; }, methods: {// Close and jump to the passed pathdoCancle() {
      this.$emit("dailog-close"."printDialogVisible");
      this.$router.push({ name: this.web_view_reback_path });
    }
  },
  watch: {
    show(item) {
      this.visiable = item;
    },
    web_view_url(newValue, oldValue) {
      this.loading = true;
      this.data_web_view_url = "/";
      setTimeout(() => {
        this.data_web_view_url = newValue;
      }, 200);
      this.loading = false; }}}; </script>Copy the code

==show== (control the display and hide of the component), == web_view_URL == (print URL), ==web_view_reback_path== (turn off the jump address after printing), Web_view_error == (whether print loading failed)

It is important to note that the prop defined in a component is a one-way data flow and can only be modified by the alignment of the parent component. The component itself cannot change the prop value, but can only change the data defined in the data. If you want to change the prop value, you can notify the parent by the custom event described below.

Solt (slot)

Let’s look at the code first

<template>
  <button>
    <slot name="icon"></slot>
    <slot></slot>
  </button>
</template>
Copy the code

A node here is the location of a slot that is specified so that the content can be extended inside the component;

<i-button>
  <i-icon slot="icon" type="checkmark"></i-icon> </i-icon>Copy the code

In this way, the contents defined in the parent will appear in the corresponding slot of the component, and the unnamed will be the default slot.

Event (event)

Let’s look at the code first

<template>
  <button @click="handleClick">
    <slot></slot>
  </button>
</template>
<script>
  export default {
    methods: {
      handleClick (event) {
        this.$emit('on-click', event);
      }
    }
  }
</script>
Copy the code

$emit triggers a custom on-click event in the component, and @on-click listens in the parent component

<i-button @on-click="handleClick"></i-button>
Copy the code

How components communicate

Vue’s components are scoped in isolation and do not allow direct references to parent data in the child component’s template. Certain methods must be used to transfer data between components

1. Communication between father and son components

The method of communication between the parent component and the child component can be passed via props: if you need to get the value of username from the parent, you do

props:{
   username:{
        
   }
}
Copy the code

A child component can pass data to its parent through an event:

 methods:{
    handelSwitch(index){
      this.actIndex=index;
      this.$emit("transferTabIndex",this.actIndex)
    }
  }
Copy the code

2. Communication between non-parent and child components: eventBus

EventBus is aimed at communication between non-parent and child components. The principle of eventBus is to trigger and listen to events.

But because they are non-parent components, they need an intermediate component to connect;

This is done by defining a component in the root component, which is the #app component, that all components can access.

There are three things we need to do to use eventBus to deliver data

  • 1. Add the Bus property to the app component (so that all components can access it via this.$root.Bus without importing any files);
  • 2. In component 1,this.Emit triggers events;
  • 3. In component 2,this.On listening event;

3. Use localized caching

This kind of communication is relatively simple, the disadvantage is that the data and state are chaotic, not easy to maintain;

Through the window. The localStorage. The getItem (key) to get the data; Through the window. The localStorage. SetItem (key, value) stored data;

Note the data format conversion with json.parse ()/json.stringify ();

Example: Baht Baoyi help center front-end components