vue中如何做到组件间数据传递
vuex
vuex作为vue的数据仓库,可以用来作为任意组件间传递数据的通道。
什么是vuex?
具体如何使用vuex传递数据,后续进行补充超链接。
$emit-prop
父组件向子组件传递参数时,可以通过子组件的props属性接受;子组件向父组件传递值时可以通过$emit向父组件传递
// 父组件
<template>
<div>
<Test :child="childData" @test="test"></Test>
</div>
</template>
<script>
// 引入子组件
import Test from './test'
export default {
name: "index",
components: {
Test
},
data(){
return {
childData: []
}
},
methods: {
test(){
console.log("接收emit事件")
}
}
}
</script>
// 子组件
<template>
<div>
<button @click="test">测试</button>
</div>
</template>
<script>
export default {
name: "Test",
components: {
Test
},
props: {
child: {
type: String,
default: ''
}
}
methods: {
test(){
this.$emit("test")
}
}
}
</script>
$emit-.sync
在父子组件传值时,子组件无法去直接修改父组件传递过来的值,但是有些情况又需要我们修改,例如修改弹窗的visible,此时,即可使用.sync修饰符。
// 父组件
<template>
<div>
<Test :visible.sync="dialogVisible"></Test>
</div>
</template>
<script>
// 引入子组件
import Test from './test'
export default {
name: "index",
components: {
Test
},
data(){
return {
dialogVisible: false
}
}
}
</script>
// 子组件
<template>
<div>
<button @click="test">测试</button>
</div>
</template>
<script>
export default {
name: "Test",
components: {
Test
},
props: {
// 非必需,可选
visible: {
type: String,
default: ''
}
},
methods: {
test(){
// update:xxx xxx为要修改的值,将要修改的值传入
this.$emit("update:visible",!visible)
}
}
}
</script>
$attrs
该用法较少,可以在父组件向孙组件传值时使用,子组件作为一个传递的中转途径。
父组件:正常引用子组件并且将值传入
<template>
<div>
<Son grandData="test"></Son>
</div>
</template>
子组件:将未使用props接收的数据,都作为html特性存入attrs中,使用v-bind="$attrs"传入孙子组件
<template>
<div>
<GrandSon v-bind="$attrs"></GrandSon>
</div>
</template>
孙子组件:孙子组件必须使用props去接收子组件使用$attrs传递的参数
<template>
<div>
{{grandData}}
</div>
</template>
<script>
export default {
name: "Test",
props: {
// 非必需,可选
grandData: {
type: String,
default: ''
}
}
}
</script>
$bus
事件总线(使用较少,可使用vuex替代)
// main.js
// 定义bus
class Bus(){
constructor(){
this.callbacks = {}
}
$on(name, fn){
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn)
}
$emit(name, args){
if(this.callbacks[name]){
this.callbacks[name].forEach(cb => cb(args))
}
}
}
// 挂载bus
Vue.prototype.$bus = new Bus()
提交时,第一个参数为事件名,第二个参数为要传递的数据
this.$bus.$emit("event","data")
接收时,在组件中做好监听。
this.$bus.$on("event", (aaa)=>{
console.log(aaa)
})