Use of components in vue.js 2.0 series

Posted by dloeppky on Fri, 01 May 2020 10:55:11 +0200

1. Creation of components

<template>
<!--vue2.0 Above, when creating a component, there must be a root element in the template-->
  <div >

  </div>
</template>

<script>
export default {
  //The purpose of not directly using the form of reference variable is to avoid that this component does not affect the data when it is used
  data () {
    return {       //Return the data used in the component in the form of function return value
      usernameModel: '',
      passwordModel: '',
      errorText: ''
    }
  },
  computed: { //The function corresponding to the calculation property will be executed when the calculation property only changes
    userErrors () {
      let errorText, status
      if (!/@/g.test(this.usernameModel)) {
        status = false
        errorText = 'Not included@'
      }
      else {
        status = true
        errorText = ''
      }
      if (!this.userFlag) {
        errorText = ''
        this.userFlag = true
      }
      return {
        status,
        errorText
      }
    },
    passwordErrors () {
      let errorText, status
      if (!/^\w{1,6}$/g.test(this.passwordModel)) {
        status = false
        errorText = 'Password is not 1-6 position'
      }
      else {
        status = true
        errorText = ''
      }
      if (!this.passwordFlag) {
        errorText = ''
        this.passwordFlag = true
      }
      return {
        status,
        errorText
      }
    }
  },
  methods: {
    onLogin () {
      if (!this.userErrors.status || !this.passwordErrors.status) {
        this.errorText = 'Some options failed'
      }
      else {
        this.errorText = ''
        this.$http.get('api/login')
        .then((res) => {
          this.$emit('has-log', res.data)
        }, (error) => {
          console.log(error)
        })
      }
    }
  }
}
</script>

<!--scoped Indicates that the current style is only valid for this component -->
<style scoped>

</style>

2. Use of components

3. Communication between parent and child components

The data is passed from the parent component to the child component by props,
In the parent component:

In the subcomponent:

There are many ways for a child component to pass information to a parent component. Here I use event passing
First, the child passes events and data to the parent

The parent component should define the corresponding processing function

4. Global components (not commonly used)