Packaging and reuse of components in Vue

When we write front-end code, we often have some controls or HMTL code fragments that are needed on many pages, and the content is almost the same, but the data is different. At this point, we can encapsulate these codes into components for us to reuse.

组件化: It is an idea to solve the simplification of complex problems, develop our programs into independent and reusable small components, and then use these small components to construct our applications.
好处: Flexible and expandable, strong reusability

Process:

  1. Package components
  2. Import already packaged components
  3. Register the used component on the use page
  4. Use packaged components

Example:
Writing subcomponents

<template>
  <!-- 封装组件 -->
  <div>
    Hello World!
  </div>
</template>

<script>
export default {
     
     
  name: "HelloWorld",
  props: {
     
     
  		user: {
     
     type: Object, default: null}
  },
}
</script>

<style scoped>
</style>

Use components: first introduce the components you want to use, then register the imported components, and finally you can use them directly

<template>
  <div>
    <!--使用组件-->
    <HelloWorld ref="helloworld" :user="user"></HelloWorld>
  </div>
</template>

<script>
// 导入要使用的组件

import HelloWorld from './hello'

export default {
     
     
  name: "hello",
  // 注册组件
  components: {
     
     
    HelloWorld
  },
  data(){
     
     
  	return{
     
     
  		user: {
     
     name:'豪华', age:18}
  	}
}
</script>

<style scoped>
</style>

Of course, when using components, it is inevitable that you need to transfer or obtain data

<script>

//父组件可以直接获取到子组件的实例,从而得到子组件的属性和方法等
this.$refs.helloworld.xxx();	//helloword是引用名,在使用组件的代码中可以看到


//而子组件则是通过 props 属性来得到父组件的数据(可结合上面示例),步骤如下:
 1. props: {
     
     user: {
     
     type: Object, default: null} }	//写于子组件中,声明属性的类型(必),默认值(选)
 2. <HelloWorld :user="user"></HelloWorld>			//在父组件引用子组件时传递即可


//子组件也可以触发父组件中的方法
 1. this.$emit('changeUser', val);		//写于子组件中,括号中写触发方法名(必)与参数(选)
 2. <HelloWorld @changeUser="changeUser"></HelloWorld>	//在父组件引用子组件时传递即可触发父组件中的 changeUser 方法

</script>

欢迎交流讨论,不对的地方请指正鸭 ~

Guess you like

Origin blog.csdn.net/weixin_45879810/article/details/113544681