The core concept of Vue components of Vue learning

what is the component

Vue components are independent small ui modules. The entire large-scale system is composed of small UI modules. The vue
insert image description here
components are vue instances. A vue instance is created by the new Vue function. Different components are just It is the difference of options, basically 90% of our development work is carried out around the configuration of options

Three Core Concepts

properties, events, slots

Attributes

insert image description here
Property example:

export default {
	name: "PropsDemo",
	// 不推荐使用这种做法,不利于维护
	// props: ['name', 'type', 'list', 'isVisible'],
	// 建议使用下面的做法来声明属性(使用对象的形式声明)
	props: {
		name: String,
		type: {
			validator: function(type) {
				// 这个值必须匹配以下字符串中的一个
				return ['success', 'warning', 'danger'].includes(value);
			}
		},
		list: {
			type: Array,
			// 对象或数组默认值必须从一个工厂获取
			default: () => []
		},
		isVisible: {
			type: boolean,
			default: false
		},
		// 不建议使用onChange来命名,会和语法冲突
		onChange: {
			type: Function,
			default: () => {}
		}
	}
}

The content of the property usage method
Props.vue file is as follows:

<template>
    <div>
        name: {
   
   { name }}
        <br>
        type: {
   
   { type }}
        <br>
        list: {
   
   { list }}
        <br>
        isVisible: {
   
   { isVisible }}
        <br>
        <button @click="handleClick">change type</button>
    </div>
</template>

<script>
export default {
    name: 'PropsDemo',
    // 自动挂载属性
    inheritAttrs: false,
    props: {
        name: String,
        type: {
            validator: function(value) {
                return ["success", "warning", "danger"].includes(value);
            }
        },
        list: {
            type: Array,
            default: () => []
        },
        isVisible: {
            type: Boolean,
            default: false
        },
        onChild: {
            type: Function,
            default: () => {}    
        }
    },
    methods: {
        handleClick() {
            // 不可以这么做,会报错, 因为我们的属性是单向数据流的,不允许在子组件内更改父组件传递过来的值
            // this.type = "warning";
            console.log("触发")
            console.log("子组件的type是:")
            console.log(this.type)
            this.onChild(123)
        }
    }
}
</script>

The App.vue file is used as follows:

<div>
    <Props
          name="Hello Vue!"
          :type="type"
          :is-visible="false"
          :on-child="handlePropChange"
          title="属性Demo"
          class="test1"
          :class="['test2']"
          :style="{ marginTop: '20px' }"
          style="margin-top: 10px;"
        />
  </div>

<script>
import Props from './components/Props.vue';

export default {
  name: 'App',
  components: {
    TodoItem,
    Props,
    // Event
  },
  data() {
    return {
      msg: "hello geek!",
      info: '',
      list: [],
      type: "success",
      name: "事件名"
    }
  },
  methods: {
    handleClick() {
        if (this.info != '') {
            this.list.push(this.info)
            this.info = ''
        }
    },
    handlePropChange(param) {
      console.log(param)
      console.log("父组件")
      if (this.type === "success") {
        this.type = "warning"
      } else {
        this.type = "success"
      }
      console.log("父组件的type")
      console.log(this.type)
    },
    handleEventChange() {

    }
  }
}
</script>

The properties are encapsulated in the child component, all of which are referenced and assigned Propswhen the parent component uses it. The child component defines a function property: , and when the parent component uses this property, it is the same as using a normal component The method of assigning values ​​is just assigning functions. Yes, functions also exist as parameters. This function can receive parameters. Whether to receive parameters and what parameters to receive depends on the definition of this function by the subcomponent. You can see There is a method in the child component , which calls onChild inside the method and passes parameters. When the method of the parent component receives the function, it also defines a parameter to receive ( )::属性名称
onChildonChild
handleClick123handlePropChangeparam

handlePropChange(param) {
      console.log(param)
      console.log("父组件")
      if (this.type === "success") {
        this.type = "warning"
      } else {
        this.type = "success"
      }
      console.log("父组件的type")
      console.log(this.type)
    }

event

insert image description here

definition Even.vuefile

<template>
    <div>
        name: {
   
   { name || '--' }}
        <br>
        <input :value="name" @change="handleChange">
        <br/>
        <br/>
        <div @click="handleDivClick">
            <button @click="handleClick">重制成功</button>
            <button @click.stop="handleClick">重制失败</button>
        </div>
    </div>
</template>

<script>
export default {
    name: 'EventDemo',
    props: {
        name: {
            type: String
        }
    },
    methods: {
        handleChange(e) {
            console.log("改变1")
            this.$emit('change', e.target.value)
            console.log("改变2")
            console.log(e.target.value)
        },
        handleDivClick() {
            console.log("清空")
            this.$emit('change', '')
        },
        handleClick() {
            // 无论做什么都会失败!
            // e.stopPropagation();
        }
    }
}
</script>

Parent component reference method:

<Event :name="eventName"  @change="handleEventChange"/>

// 导入
import Event from './components/Event.vue';

// 方法定义
handleEventChange(param) {
  console.log("父组件接收到change事件")
  if (param?.target?.value) {
    this.eventName = param?.target?.value
    console.log(param?.target?.value)
  } else {
    this.eventName = ""
  }
}

Child component definition method: handleChange, through this.$emit('change', e.target.value), calling the change method, passing the value of the current input box as a parameter The parent component receives it
through a function, and declares a parameter: , obtains the passed parameter value throughhandleEventChangeparamparamparam?.target?.value

slot

insert image description here

Create a new file in the component folder: Slot.vue

<template>
    <div>
        <slot />
        <slot name="title" />
        <slot name="item" v-bind="{ value: 'vue' }" />
    </div>
</template>
<script>
export default {
    name: "SlotDemo"
}
</script>

Parent component reference part:

<SlotDemo>
  <template v-slot:title>
    <p>title slot1</p>
    <p>title slot2</p>
  </template>
  <template v-slot:item="props">
    <p>item slot-scope {
   
   { props }}</p>
  </template>
</SlotDemo>

// js引用
import SlotDemo from './components/Slot.vue';

name="title"The child component refers to the slot defined by the child component through the defined slot name="item"and slot, and the parent component references the slot defined by the child component through v-slot:titleandv-slot:item="props"

Summarize

insert image description here

Guess you like

Origin blog.csdn.net/wwrzyy/article/details/132489190