组件之间传参方式:
- 父子Coms: 1-12
- 兄弟Coms: 4/5/11/12
- 跨级Coms: 4/5/6/7/11/12
- props 父传子
- $emit 子传父 (最常用的父子通讯方式)
- (
p
a
r
e
n
t
s
/
parents/
parents/children )
- $refs 常用于父组件调用子组件的方法(如:列表数据变化通知子组件重新渲染列表等)
- Vuex 用于任意组件的任意通讯
- Bus (常用任意两个组件之间通讯)
- ( provide/inject ) (祖先及其后代传值)常用一些多个组件嵌套封装,一个顶层组件内部的后代组件需要用到顶层组件的数据就使用这种方式
- (
a
t
t
r
s
/
attrs/
attrs/listeners ) (常用于对原生组件的封装) $attrs 可以获取父组件传进来但没有通过props接收的属性
- .sync (可以帮我们实现父组件向子组件传递的数据 的双向绑定)
- v-model(和 .sync 类似,可以实现将父组件传给子组件的数据为双向绑定,子组件通过 $emit 修改父组件的数据)
- $root(可以拿到 App.vue 里的数据和方法)
- slot(把子组件的数据通过插槽的方式传给父组件使用,然后再插回来)
Bus
class Bus {
constructor () {
this.callbackList = {}
}
$on (name, callback) {
this.callbackList[name] ? this.callbackList[name].push(callback) : (this.callbackList[name] = [callback])
}
$emit (name, args) {
if (this.callbackList[name]) {
this.callbackList[name].forEach(cb => cb(args))
}
}
}
Vue.prototype.$bus = new Bus()
this.$bus.$on('confirm', handleConfirm)
this.$bus.$emit('confirm', list)
(
p
a
r
e
n
t
s
/
parents/
parents/children )
this.$patent.$on('confirm', handleConfirm)
this.$patent.$emit('confirm', list)
console.log(this.$children[0].msg)
this.$root.handleRoot()
$ref
<hello-world ref="hello"></hello-world>
export default {
mounted(){
this.$refs.hello.handleRef()
}
}
provide/inject
export default {
provide(){
return {
msg: 'hello world!'
}
}
}
export default {
inject: ['msg']
}
$listeners 会展开父组件的所有监听的事件(click事件等)常用于更高层级的封装** **举个例子(需求):一个页面中有两个组件的点击事件触发方法是一样的"
<div>
<child-first @click="handleClick"></child-first>
<child-second @click="handleClick"></child-second>
</div>
export default {
methods: {
handleClick: (){
alert('hello')
}
}
}
<div v-on="$listeners"></div>
<div v-on="$listeners"></div>
.sync
<template>
<child :page.sync="page"></child>
</template>
<script>
export default {
data(){
return {
page:1
}
}
}
export default {
props:["page"],
computed(){
currentPage {
get(){
return this.page
},
set(newVal){
this.$emit("update:page", newVal)
}
}
}
}
</script>
v-model
<template>
<child v-model="value"></child>
</template>
<script>
export default {
data(){
return {
value:1
}
}
}
<template>
<input :value="value" @input="handlerChange">
</template>
export default {
props:["value"],
model:{
event:"updateValue"
},
methods:{
handlerChange(e){
this.$emit("input", e.target.value)
this.$emit("updateValue", e.target.value)
}
}
}
</script>
slot
<template>
<div>
<slot :user="user"></slot>
</div>
</template>
export default{
data(){
return {
user:{ name:"沐华" }
}
}
}
<template>
<div>
<child v-slot="slotProps">
{{ slotProps.user.name }}
</child>
</div>
</template>