属性
子组件:
<template>
<div>
{{ 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', 'type', 'list', 'isVisible'],
props: {
name: String,
type: {
validator: function(value) {
// 这个值必须匹配下列字符串中的一个
return ["success", "warning", "danger"].includes(value);
}
},
list: {
type: Array,
// 对象或数组默认值必须从一个工厂函数获取
default: () => []
},
isVisible: {
type: Boolean,
default: false
},
onChange: {
type: Function,
default: () => {}
}
},
methods: {
handleClick() {
this.onChange(this.type === "success" ? "warning" : "success");
}
}
};
</script>
<style scoped>
.test2 {
margin-left: 5px
}
.test1 {
margin-left: 50%
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
父组件
<props-vue
:name="name"
:type="type"
:is-visible="false"
:on-change="handlePropChange"
title="属性Demo"
class="test1"
:class="['test2']"
:style="{ marginTop: '20px' }"
style="margin-top: 10px"
/>
1
2
3
4
5
6
7
8
9
10
11
注意事项
如果子组件未定义的属性,父组件中定义如果想去掉则在子组件中设置inheritAttrs: false即可
事件
子组件
<template>
<div>
name: {{ name || "--" }}
<br />
<input :value="name" @change="handleChange" />
<br />
<br />
<div @click="handleDivClick">
<button>重置成功</button>
<button @click.stop="handleClick">重置失败</button>
</div>
</div>
</template>
<script>
export default {
name: "EventDemo",
props: {
name: String
},
methods: {
handleChange(e) {
// 将输入框值传给父组件
this.$emit("giveValue", e.target.value);
},
handleDivClick() {
this.$emit("giveValue", "");
},
handleClick(e) {
// 都会失败
e.stopPropagation();
}
}
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
父组件
<event :name="name" @giveValue="handleEventChange"></event>
handleEventChange(val) {
this.name = val;
}
1
2
3
4
注意事项
emit将子组件中属性传给父组件,this. emit 将子组件中属性传给父组件,this.emit将子组件中属性传给父组件,this.emit(“giveValue”,value) 第一个为父组件接受的方法名,第二个值为传入的参数
插槽
普通插槽
子组件
<slot />
1
父组件
<slot-demo>
<p>default slot</p>
</slot-demo>
1
2
3
具名插槽
子组件
<slot name="title" />
1
父组件
<slot-demo>
<template v-slot:title>
<p>title slot1</p>
<p>title slot2</p>
</template>
</slot-demo>
1
2
3
4
5
6
作用域插槽
子组件
<slot name="item" v-bind="[{ value: 'vue' },{name:'slot'}]" />
1
父组件
<template v-slot:item="props">
<p>item slot-scope {{ props }}</p>
</template>
</slot-demo>
1
2
3
4
代码传送门
---------------------
作者:愤怒的小猥琐
来源:CSDN
原文:https://blog.csdn.net/qq_32890891/article/details/88954634
版权声明:本文为博主原创文章,转载请附上博文链接!