父传子 主要通过props实现
父组件通过import引入子组件,并注册,在子组件标签上添加要传递的属性,
子组件通过props接收,接收的形式有两种
可以传递单个值或者多个值,基本数据类型或者引用数据类型都可
<template>
<div class="home">
<item :name="name">
</item>
</div>
</template>
<script>
//父组件
import Item from '@/components/Item.vue';
export default {
name: 'HomeView',
components: {
Item
//Item: () => import('@/components/Item.vue')//这是组件懒加载的引入方式
},
data() {
return {
name: 'jerry'
}
}
}
</script>
1.数组形式接收参数
数组只是简单的接收
//子组件
export default{
props:['list']
}
2.对象形式接收参数
对象形式可以设置要传递的数据类型和默认值。
//子组件
export default{
props:{
list:{
type:Array,
default:()=>[]
}
}
}
需要注意的是父子组件传值是单向的,在子组件里无法改变父组件的值(复杂数据类型除外),如果直接修改props的值会报错。
子传父 主要通过$emit
通过点击事件触发函数,在函数中通过$emit方法设置自定义事件和要传递的值
<template>
<div @click="changeFn">
{{ name }}
</div>
</template>
<script>
//子组件
export default {
props: ['name'],
methods: {
changeFn() {
this.$emit('setName', 'Tom')
}
}
};
</script>
父组件里在子组件标签上@自定义事件,通过函数的默认参数拿到子组件传递的值
<template>
<div class="home">
<item :name="name" @setName="setName">
</item>
</div>
</template>
<script>
export default {
name: 'HomeView',
components: {
Item: () => import('@/components/Item.vue')
},
data() {
return {
name: 'jerry'
}
},
methods: {
setName(val) {
console.log(val, '父组件');
this.name = val
}
}
}
</script>
上图片
通过子组件点击事件触发$emit把父组件传递给子组件的值改变了
兄弟组件之间的通讯
通过event.bus实现
创建一个空的vue暴露出去,这个作为公共的bus,当做两个组件的桥梁,在两个兄弟组件中分别引入bus,在组件one中bus.on接收
<template>
<div @click="changeFn">
one组件
</div>
</template>
<script>
import bus from '@/utils/eventBus'
export default {
methods: {
changeFn() {
bus.$emit('setName', 'Tom')
}
}
};
</script>
<template>
<div>
tow组件
{{ name }}
</div>
</template>
<script>
import bus from '@/utils/eventBus'
export default {
data() {
return {
name: ''
};
},
created() {
bus.$on('setName', (val) => {
this.name = val
})
}
};
</script>
父组件引入两个子组件
<template>
<div class="home">
<one-view>
</one-view>
<two-view>
</two-view>
</div>
</template>
<script>
export default {
name: 'HomeView',
components: {
oneView: () => import('@/components/OneView.vue'),
twoView: () => import('@/components/TwoView.vue')
},
data() {
return {
}
},
methods: {
}
}
</script>
one组件点击触发bus.emit传递数据,two接收值,渲染到页面上
通过vuex实现
具体实现: vuex是一个状态管理工具,主要解决大中型复杂项目的数据共享问题,主要包括state, actions,mutations, getters和 modules 5个要素,主要流程:组件通过dispatch到 actions,actions是异步操作,再actions中通过commit到mutations,mutations再通过逻辑操作改变state,从而同步到组件,更新其数据状态