vue组件传值(vue组件通信)的几种方式
我们接触了vue.js 之后,组件化的开发 不得不让我们用到传值。
一:父传子(props)
具体实现:父组件通过import引入子组件,并注册,在子组件标签上 添加要传递的属性,子组件通过props接收,接收有两种形式一是通过数组 形式[‘要接收的属性’],二是通过对象形式{}来接收,对象形式可以设 置要传递的数据类型和默认值,而数组只是简单的接收。
1.1 数组形式接收
父组件展示:
<template>
<div>
这里是父组件呦~我引入了子组件
<son :title="this.title" />
</div>
</template>
<script>
// @ is an alias to /src
import son from "../components/son";
export default {
name: "Home",
data: function() {
return {
title: "你今天快乐吗"
};
},
components: {
son
}
};
</script>
子组件展示:
<template>
<div>
我是子组件啦
<br />
父组件传递过来的值~=={{title}}
</div>
</template>
<script>
export default {
props: ["title"], //数组形式 不能接受传递过来的数据类型
data() {
return {};
}
};
</script>
<style scoped>
</style>
1.2 对象形式接收
父组件:
<template>
<div>
这里是父组件呦~我引入了子组件
<son :title="this.list" />
</div>
</template>
<script>
// @ is an alias to /src
import son from "../components/son";
export default {
name: "Home",
data: function() {
return {
// title: "你今天快乐吗",
list:[1,2,3,4]
};
},
components: {
son
}
};
</script>
子组件:
<template>
<div>
我是子组件啦
<br />
父组件传递过来的值~==
<div v-for="(item,index) in list" :key="index">
{{item}}
</div>
</div>
</template>
<script>
export default {
// props: ["title"], //数组形式 不能接受传递过来的数据类型
data() {
return {};
},
props:{
list:{
type:String,//接收传递的类型
require:true//必填项及,一旦写了这个 如果不进行遍历使用的会报错!!!
default:'请输入'//默认显示
}
}
};
</script>
<style scoped>
</style>
那么还有个问题就是,我们子组件的修改能否同步到父组件 ,当然我们可以改变prop的值,来更新父组件 -sync修饰符
//父组件中:
<div:title.sync="{{title}}"></div>
//子组件中: 实现双向数据流
this.$emit('update:title",'111')
二:子传父($emit)
父组件中:
<template>
<div>
这里是父组件呦~我引入了子组件
<son :title="this.list" @give="up" />
</div>
</template>
<script>
// @ is an alias to /src
import son from "../components/son";
export default {
name: "Home",
data: function() {
return {
// title: "你今天快乐吗",
list: [1, 2, 3, 4]
};
},
components: {
son
},
created: {},
mounted() {},
methods: {
up(value) {
console.log(value);
}
}
};
</script>
子组件中:
<template>
<div>
我是子组件啦
<!-- <br />父组件传递过来的值~== -->
<button @click="giveDad">传递给父组件</button>
<!-- <div v-for="(item,index) in list" :key="index">{{item}}</div> -->
</div>
</template>
<script>
export default {
// props: ["title"], //数组形式 不能接受传递过来的数据类型
data() {
return {
arr: [888, 999, 111, 222, 555]
};
},
props: {
list: {
type: String
}
},
methods:{
//发送自定义事件
giveDad(){
this.$emit('give',this.arr)
// console.log('111',this.arr)
}
}
};
</script>
<style scoped>
</style>
三:如何在父组件中调用子组件的方法:
ref:通过ref给dom元素或组件本身添加名称来实现
例如:
JS中通过this. r e f s . 名 子 访 问 例 如 : t h i s . refs.名子访问 例如:this. refs.名子访问例如:this.refs.dialog
四:兄弟传值
在任意两个组件传值中,可以创建一个bus类负责事件派发、监听和回调管理。
使用方式
在Vue项目中,我a.vue需要给b.vue传值,使用bus传值的方式如下:
1)建立bus.js文件
在文件夹下建立bus.js文件,写入以下代码:
// bus.js
import Vue from 'vue'
export default new Vue()
2)a.vue中添加代码
// 引入公共的bus,来做为中间传达的工具
import Bus from '../../api/bus'
beforeDestroy(){
Bus.$emit('val', 要传递的值)
console.log('我发送成功了');
},
3)b.vue中添加代码
import Bus from '../../api/bus'
created(){
// 用$on事件来接收参数
Bus.$on('val', (data) => {
console.log(data)
})
}
今天就跟大家分享到这里嘻嘻嘻~