vue component, non single file component, single file component, inter component operation (note)

1. Components and modules

1.1 module

  1. If the code in a js file, many are very complex
  2. Modules can be used to store different js files in different logical segments and import them into a main file
  3. It simplifies the writing of code and improves the reuse of code

1.2 components

  1. To achieve the effect of a function, a collection of codes
  2. The codes of html, css and js are stored in one file, which solves the problem of introducing multiple css and js files into an html file
  3. The reuse rate of components is very high. If the same function is placed in one component, other components can be introduced

1.3 modularization and componentization

  • Modular development: when js in an application are written in modules, the application is a modular application
  • Component development: when the functions in an application are written with components, the application is a component application

2. Use of non single file components

2.1 two ways of writing data and el

// Some concepts need to be understood before creating components
// 1. Two ways of writing el
new Vue({ // Configuration on Creation
  el: "#app" 
})
new Vue({}).$mount("#app ") / / Mount after creation

// 2. Two ways of writing data
data:{} // Object type
data(){ return {} } // Functional expression (this must be used in components, and private attributes are created through closures)

2.2 steps for using components

  1. Create component
  2. Register components
  3. Use component (write component label)
<div id="app">
  <!-- Using components -->
  <School></School>
  <Student></Student>
</div>
// Create component
let school = Vue.extend({
  // Rendering views through template
  template: `
    <div>
      <h2>{{msg}}</h2>  
    </div>
  `,
  data() {
    return {
      msg: "I am a school"
    }
  }
})

let student = Vue.extend({
  template: `
    <div>
      <h2>{{msg}}</h2>  
    </div>
  `,
  data() {
    return {
      msg: "I am a student"
    }
  }
})

// Registration component, global registration
// Vue.component("School", school)
// Vue.component("Student", student)

const vm = new Vue({
  el: "#app",
  data: {
    msg: "I am vue example"
  },
  // Registration component, partial registration
  components: {
    school,
    student
  }
})

2.3 precautions for using components

  • Register component name

    One word: school, School

    Multiple words: my school, myschool (Vue scaffold support required)

    be careful:

    1. Element names in HTML tags cannot be used
    2. Add name to the configuration item to specify the component name, which will be presented in the Vue developer tool
    3. If you do not add name, it defaults to the component name
  • Using component labels

    It is composed of one word: < School > < / School >, < school / > (scaffold support is required), and it is best to distinguish between initial capitalization and HTML tag

    Multiple words: < My School > < / my school >, < my school / >, < myschool > < / myschool >, < my school / >

  • Create component

    // In the latter case, Vue will call extend by default when registering components
    let school = Vue.extend(options) ==> let school = options
    

2.4 component nesting

<div id="app">
<School></School>
</div>
let student = {
  template: `
    <div>
      <h2>{{msg}}</h2>  
    </div>
  `,
  data() {
    return {
      msg: "I am a student"
    }
  }
}

let school = {
  // Here are student s registered in school, which can only be used in school
  // The tag name should be the same as the registered name of the component and case sensitive
  template: `
    <div>
      <h2>{{msg}}</h2>  
      <student></student>
    </div>
  `,
  components: {
    student
  },
  data() {
    return {
      msg: "I am a school"
    }
  }
}

const vm = new Vue({
  el: "#app",
  data: {
    msg: "I am vue example"
  },
  components: {
    school
  }
})

2.5 Vuecomponent

Every call to Vue Extend generates a new Vuecomponent constructor, that is, a component

When we write components on the page, Vue will execute new Vuecomponent() for us

2.6 relationship between Vue instances and components

  • There can only be one instance. The instance has el attribute. The data of the instance can be an object or function. The instance needs to be mounted based on a view
  • There can be multiple components. Components have no el attribute. Component data can only be functions. Components can be reused
  • Vuecomponent.prototype.__proto__ === Vue.prototype

‚Äč

3. Use of component documents

3.1 understanding

  • The suffix is vue files need to be compiled into js files with the help of webpack or vue cli (scaffold) before they can be used
  • vue files are generally named school vue or myschool vue, a large hump, corresponds to the component name

3.2 document structure

<template>
  <div class="demo">
    <!-- structure -->
  </div>
</template>

<script>
export default {
  // logic
  name: "Demo",
  data() {
    return {
      msg: "I am a single file component",
    };
  },
};
</script>

<style>
/* style */
.demo {
  background-color: aqua;
}
</style>

4. Operation between components

4.1 ref attribute

  • When applied to the html tag, the real DOM element is obtained, and when applied to the component tag, the component instance object is obtained

  • Usage

    Add: < H1 ref = "XXX" > Hello < / H1 > or < school ref = "XXX" / >

    Get: this$ refs. xxx

4.2 props configuration

  1. Function: let the component receive the data from the outside

  2. Transfer data: < Demo name = "data / function" / >, and Demo is the component label

    • If the incoming value is data, this method is passed from parent to child
    • If the incoming value is a function, the callback function returns the value to the outside. In this way, the child passes the parent
  3. Receive data:

    1. The first method only receives the value: props:['name ']

    2. The second way is to limit the type of value passed: props:{name:String}

    3. Third, multiple configuration items:

      props: {
        name: { // Transfer value
        type: String, // Pass value type
        required: true, // Must pass value
        default: 'aaa' // Default value
        }
      }
      

    be careful:

    • You can get the value in props in data, and props should be executed first
    • props should follow the one-way data flow, that is, the data transmitted from the parent component. It is best not to modify it, which will change the data of the parent component. This design is a shallow copy. If it is not necessary to use it, you can make a deep copy of the value transmitted from the parent component for use (this data refers to the reference data type)

4.3 mixin mixing

  1. Function: the configuration shared by multiple components can be extracted into a mixed object

  2. Usage:

    Step 1: define mixing: export required

    // Define public configuration items in a js file
    export default {
        data() {....},
        methods: {....}
        ....
    }
    

    Step 2: use blending: import is required

    // Global blending
    Vue.mixin(xxx)
    
    // Local mixing, written in the configuration object
    mixins:['xxx'] // Must be an array
    

    be careful:

    If the mixed object configuration conflicts with the component object configuration, if it cannot be combined, the component object configuration will prevail, and if it can be combined, it will be used in combination (the data conflict can not be combined)

4.4 plug in

Role of plug-in: to enhance Vue

// js file
export default {
  // You can write some global public API s in this file
  install(Vue, a, b){ 
	// Vue: Vue constructor
    // a: Passed in parameter 1
    // b: Passed in parameter 2
  }
}
// vue file
import Plugins from "File path"
Vue.use(Plugins, 1, 2)

4.5 scoped style

  1. Function: make styles take effect locally to prevent conflicts
  2. Writing method: < style scoped >
  3. Principle: add a data-v-xxxxx attribute to each label, and add a style through the attribute selector
  4. Note: the scoped of the parent component will add the same data-v-xxxxx attribute to the root element of the child component

4.6 custom events

  • This method is applicable to the transfer from child to parent. The callback function of the parent component is triggered through the custom event of the child component

  • Bind custom events:

    1. The first method is in the parent component: < demo @ haha = "function in parent component" / >

    2. In the second way, in the parent component:

      <Demo ref="demo"/> // Demo is a child component written in the parent component
      ......
      mounted(){
         // $on can bind multiple events, $on (["haha", "heiheihei"])
         this.$refs.demo.$on("haha", function (receive data ){
      	// Here, this of the function points to the sub component, because it is a custom event triggered by the sub component
        })
      }
      
    3. If you want a custom event to be triggered only once, you can use the once modifier or the $once method

  • Trigger custom event: this$ Emit ("haha", incoming data)

  • Unbind custom event:

    • Unbind one: this$ off("haha")
    • Unbind multiple: this$ off(["haha", "heihei"])
    • Unbind all: this$ Off(), all refers to all of the current component
  • You can also bind native DOM events on the component, and you need to use the native modifier

4.7 global event bus

  • Communication between any components

  • Install event bus:

    new Vue({
      ......
      beforeCreate() {
        // To put it bluntly, it is to mount the instance to the $bus of the prototype and pass through the prototype chain
        // In this way, all other components can be through this$ Bus bind / trigger / unbind events
    	Vue.prototype.$bus = this
      },
      ......
    }) 
    
  • Using the event bus:

    • Receive data and bind events

      this.$bus.$on("haha", (data)=>{})
      
    • Provide data and trigger events

      this.$bus.$emit("haha", data)
      
    • Unbinding event

      this.$bus.$off("haha")
      
  • It is better to unbind the event bus in the current component in the beforeDestroy hook. Never use this$ bus.$ off()

4.8 message subscription and publication

  • Communication between any components

  • Use steps:

    • Install pubsub: NPM I pubsub JS

    • Import: import PubSub from 'PubSub JS'

    • Receive data and add subscriptions

      // An id will be returned 
      this.pid = pubsub.subscribe('haha',(msgName, data)=>{})
      
    • Provide data, publish and subscribe

      pubsub.publish('xxx',data) // Only two parameters can be passed
      
    • Unsubscribe

      PubSub.unsubscribe(this.pid) // Cancel by returned id name
      

4.9 nextTick

  • Syntax: this$ Nexttick (callback function)
  • Function: execute callback after the next DOM update. The effect is the same as that of setTimeout
  • When to use: after changing the data, you need to get the DOM operation

Tags: Vue Vue.js

Posted by saeeddeep on Mon, 18 Apr 2022 04:28:16 +0300