SoFunction
Updated on 2025-04-12

Example explanation of using components component

Using components

Structure of component (vue file)

<!--Page templates-->
<template>
  <div> {{msg}}</div>
</template>
<!--JS Module Object-->
<script>
  export default {
    data () {
      return {msg: 'vue template page'}
    }
  }
</script>
<!--cssstyle-->
<style>
</style>

Basic use of components

  • Introducing components
  • Map into tags
  • Use Component Tags
<template>
  <!--3.Use Component Tags-->
  <HelloWorld/>
</template>
<script>
  //1.Introduce components  import HelloWorld from './components/'
  export default {
    //2. Map component tags    components: {
      HelloWorld
    }
  }
</script>

vue defines component components (local/global)

Basic information

Components are an extension of your html tags

The content in the component is the content of your template

Components are divided into global components and local components

The components defined in the object are local components

How to define (register) components

  • Defining components requires the components option. components is an object whose properties are the relevant configuration information of the component.
  • At least the template attribute or render method should be included in the component.
  • When using it, you can use the name of the component as a tag.

Notice:

When your component name is named by camel, when using component, the lowercase and uppercase should be divided by -.

The data in the component is not shared with the instances outside it.

Data defined within a component (data)

  • Must be a function
  • The function must have a return value
  • The return value must be an object

Local components

<Zujian></Zujian>  // html You can use already defined components in
new Vue({
    el:"#root",
    data:{
    ... ...
    },
    components:{     // You can see that components are plural forms, which means that we can define multiple components here    Zujian:{         //Define a component named zujian //It is an object form        template:`<div>Define a component,The name is zujian </div>`    //Component specific content        }
    }
})

Global Components

('Zujian', {    //Writing outside of new Vue //Writing in script  template: `<div>Define a component,The name is zujian </div> `
})
<Zujian></Zujian>  // html You can use already defined components in

Introducing external components

//Introduce external components<script>
import Zujian from './components/'
export default{
    data(){
        return{
            ... ...
        }
    },
    components:{
        Zujian
    }
}
</script>
//External components<template>
    <div>hello world!!!</div>
<template>
<script>
    ... ...
</script>

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.