一. 父传子
1、在父组件的子组件标签上绑定一个自定义属性,挂载要传输的数据
2、在子组件中通过props属性来接受传递的数据格式 props:[“自定义属性名”] 接受的数据可以直接使用
父组件内代码
<template>
<div>
<lxcf :data='name'/>
</div>
</template>
<script>
import lxcf from './lxcf'
export default {
components: {lxcf},
data() {
return {
name:'晴空万里'
};
},
mounted() {},
methods: {
},
};
</script>
<style scoped></style>
子组件内代码
<template>
<div>
<h2>{{data}}</h2>
</div>
</template>
<script>
export default {
components: { },
props:['data'],
data() {
return {
};
},
mounted() {},
methods: {
},
};
</script>
<style scoped></style>
二. 子传父
1、在父组件的子组件标签上自定义一个事件,挂载要调用的方法
2、在子组件的事件中通过this.
e
m
i
t
来
触
发
绑
定
在
子
组
件
的
事
件
格
式
t
h
i
s
.
emit来触发绑定在子组件的事件 格式 this.
emit来触发绑定在子组件的事件格式this.emit(“事件名”)要传输的数据以参数的形式进行传递
父组件内代码
<template>
<div>
<lxcf :data='name' @fct='fct'/>
</div>
</template>
<script>
import lxcf from './lxcf'
export default {
components: {lxcf},
data() {
return {
name:'前端攻城狮'
};
},
mounted() {},
methods: {
fct(val){
this.name=val
}
},
};
</script>
<style scoped></style>
子组件内代码
<template>
<div>
<h2>{{data}}</h2>
<button @click="fuct">点我</button>
</div>
</template>
<script>
export default {
components: { },
props:['data'],
data() {
return {
};
},
mounted() {},
methods: {
fuct(){
this.$emit('fct','这是子传父')
}
},
};
</script>
<style scoped></style>
三. 兄弟组件通信
1、在src中新建一个Bus.js的文件,然后导出一个空的vue实例
2、在传输数据的一方引入Bus.js 然后通过Bus.
e
m
i
t
(
“
事
件
名
”
,
"
参
数
"
)
来
来
派
发
事
件
,
数
据
是
以
emit(“事件名”,"参数")来来派发事件,数据是以
emit(“事件名”,"参数")来来派发事件,数据是以emit()的参数形式来传递
3、在接受的数据的一方 引入 Bus.js 然后通过 Bus.$on(“事件名”,(data)=>{data是接受的数据})
父组件内的代码
<template>
<div>
<son1 @xs="xs" />
<son2 v-show="flag" @xs="xs"/>
</div>
</template>
<script>
import son1 from "./son1";
import son2 from "./son2";
export default {
components: { son1, son2 },
name: "",
data() {
return {
flag: false,
};
},
mounted() {},
methods: {
xs() {
this.flag = !this.flag;
},
},
};
</script>
<style scoped></style>
子组件一内的代码
<template>
<div><input type="text" @click='xianshi' v-model="name"><button>搜索</button></div>
</template>
<script>
import bus from '@/bus'
export default {
components: { },
name: '',
data() {
return {
name:''
};
},
mounted() {},
methods: {
xianshi(){
this.$emit('xs')
bus.$on('suibian',(data)=>{
this.name = data
})
}
},
};
</script>
<style scoped></style>
子组件二内的代码
<template>
<div>
<ul>
<li v-for='(item,index) in list' :key='index' @click="add(item.name)">{{item.name}}</li>
</ul>
</div>
</template>
<script>
import bus from '@/bus'
export default {
components: {},
name: "",
data() {
return {
list: [
{ id: 1, name: "熊大" },
{ id: 2, name: "熊二" },
{ id: 3, name: "熊三" },
],
};
},
mounted() {},
methods: {
add(name){
this.$emit('xs')
bus.$emit('suibian',name)
}
},
};
</script>
<style scoped></style>
bus.js内的代码
import Vue from 'vue'
export default new Vue({})