vue组件化

261 阅读1分钟

vue组件化实战

(一)组件化:vue组件系统提供了⼀种抽象,让我们可以使⽤独⽴可复⽤的组件来构建⼤型应⽤,任意类型的应⽤界 ⾯都可以抽象为⼀个组件树。组件化能提⾼开发效率,⽅便重复使⽤,简化调试步骤,提升项⽬可维护 性,便于多⼈协同开发。

(二)组件的通信方式: 组件通信常用方式:1.props;2.event;3.vuex 自定义事件:1.边界情况(1.parent;2.parent;2.children;3.root;4.refs;5.provide/inject2.prop特性(1.refs;5.provide/inject) 2.非prop特性(1.attrs;2.$listeners)

**例子:**
1)props⽗给⼦传值
//child
props:{msg:String}
//parent
<HelloWord msg="hi ruby"/>

2)自定义事件 子给父传值
//children
this.$emit("add",good)
//parent
<Cart @add="cartAdd($event)"></Cart>

3)事件总线 任意2个组件之间的传值常用事件总线或vuex的方式
//bus:事件派发,监听和回调管理
class Bus{
 constructor(){
   this.callback={}
  }
  $on(name,fn){
  this.callbacks[name]=this.callback[name]|[]
  this.callbacks[name].push(fn)
  }
  $emit(name,args){
    if(this.callbacks[name]){
      this.callbacks[name].forEach(cb=>cb(args))
    }
  }
}
//main.js
Vue.prototype.$bus=new Bus();
//childs1
this.$bus.$on("foo",handle)
//child2
this.$bus.$emit('foo')
注意:实践中通常用vue替代bus,因为vue已经实现了相应的接口

4)vuex创建唯一的全局数据管理者store,通过它管理数据并通知组件状态的变更。

5)$parent/$root兄弟组件之间的通信可通过共同的祖辈搭桥,$parent或$root.
//brother1
this.$parent.$on('foo',handle)
//brother2
this.parent.$emit("foo")

6)$children 父组件可以通过$children访问子组件实现父子通信
//parent
this.$children[0].xx='XXX'
注意:$childern不能保证子元素的顺序,因为有异步组件

7)$attr/$listeners
    包含了⽗作⽤域中不作为 prop 被识别 (且获取) 的特性绑定 ( class 和  style 除外)。 当⼀个组件没有声明任何 prop 时,这⾥会包含所有⽗作⽤域的绑定 ( class 和  style 除外),并且可以通过  v-bind="$attrs" 传⼊内部组件——在创建⾼级别的组件时⾮常有⽤。
//child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
//parent
<HelloWorld foo="foo"/>

8)refs获取子节点引用
//parent
<HelloWorld ref="hw"/>
mounted(){
 this.$refs.hw.xx='XXX'
}

8)provide/inject能够实现祖先和后代之间的传值
//ancestor
provide(){
 return {foo:'foo'}
}
//descendant
inject:['foo']

**(三) 组件自定义事件---子组件直接修改父组件值的方法 **

1.利用v-model

(1)组件IncreaseButton.vue

<template>
	<el-button type="primary" @click="increase"> {{innerValue}}</el-button>
</template>
<script>
export default {
	name: "IncreaseButton",
	model: {
		prop: "value",
		event: "update"
	},
	props: {
		value: {
			type: Number,
			default: 0
		}
	},
	computed: {
		innerValue: {
			get() {
				return this.value;
			},
			set(innerValue) {
				this.$emit("update", innerValue);
			}
		}
	},
	methods: {
		increase() {
			this.innerValue++;
		}
	}
}
</script>

(2)组件使用

<increase-button v-model="num"></increase-button>
<el-input v-model.number="num" style="width: 40px"></el-input>

注意:v-model实现数据的双向绑定,利用名为value的prop和名为update的事件,实现双向绑定。因为子组件不能修改父组件传过来的prop的值。再结合利用get,set方法,实现子组件能够修改父组件传过来的值

一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像单选框、复选框等类型的输入控件可能会将 value attribute 用于不同的目的.model 选项可以用来避免这样的冲突.

2.利用sync修饰符 (1)组件

<template>
	<el-select v-model="innerValue" @change="change" >
            <el-option v-for="option in options" :key="option.value" :value="option.value" :label="option.label" ></el-option>
        </el-select>
</template>

<script>
export default {
	name: "ValueLabelSelect",
	props: {
		options: {
			type: Array,
		},
		value: [Number, String],
		label: String,
	},
	watch: {
		value: {
			handler(value) {
				this.innerValue = value;
			},
			immediate: true,
		},
	},
	data() {
		return {
			innerValue: undefined,
		};
	},
	methods: {
		change(value) {
			for (const option of this.options) {
				if (option.value === value) {
					this.$emit("update:value", value);
					this.$emit("update:label", option.label);
					break;
				}
			}
		},
	},
};
</script>

(2)组件的使用

 <value-label-select :value.sync="value" :label.sync="label" :options="options">
     <div> Value: {{value}}</div>
     <div> Label: {{label}}</div>
 </value-label-select>

注意:通过watch将prop传过来的值赋值给innerValue;当修改innerValue值时,触发

this.$emit("update:value", value);

this.$emit("update:label", option.label);事件从而达到修改父组件值。

**(四) 插槽 **

插槽语法是Vue 实现的内容分发 API,⽤于复合组件开发。该技术在通⽤组件库开发中有⼤量应⽤。 1)匿名插槽

 // comp1
 <div>
    <slot></slot>
</div>
//parent
 <comp>hello</comp>

2)具名插槽

// comp2
<div>
<slot></slot>
<slot name="content"></slot>
</div>
// parent
<Comp2>
<!-- 默认插槽⽤default做参数 -->
<template v-slot:default>具名插槽</template>
<!-- 具名插槽⽤插槽名做参数 -->
<template v-slot:content>内容...</template>
</Comp2>

3)作⽤域插槽:分发内容要⽤到⼦组件中的数据

// comp3
<div>
<slot :foo="foo"></slot>
</div>
// parent
<Comp3>
<!-- 把v-slot的值指定为作⽤域上下⽂对象 -->
<template v-slot:default="slotProps">
来⾃⼦组件数据:{{slotProps.foo}}
</template>
</Comp3