前言
Vue组件传值是指在Vue组件之间传递数据或者事件,主要有以下几种方式
- 子组件向父组件传值
- 父组件向子组件传值
- 兄弟组件之间传值
- 跨级组件传值
- 使用Vuex进行组件之间的数据共享
这里简单介绍一下前两种
1.子组件向父组件传值
子组件向父组件传值:在父组件中给引用的子组件注册一个自定义事件,在子组件中使用$emit(‘事件名称’)触发
示例:
父组件
// 父组件
Vue.component('parent', {
template: '#father',
data() {
return {
quick: 'free'
}
},
methods: {
transfer(dats,dats2) {
console.log(dats);
console.log(dats2);
}
}
})
子组件
Vue.component('children', {
template: '#child',
data() {
return {
}
},
props: {
matype: {
type: [String, Number],
default: () => {
return 'free'
}
}
},
created() {
console.log(this.matype);
},
methods: {
tofa() {
// 第一个参数:自定义的名字
//第二个参数:传递的数据
this.$emit('tofather', '传过去的数据')
this.$emit('tofather', { name: 'zs', age: 18 })
}
}
})
2.父组件向子组件传值
父组件向子组件传值:在父组件的子标签中写一个自定义属性,在子组件中用props接收
示例:
父组件子标签
<div id='app'>
<!-- <h2>免费课程</h2> -->
<!-- 自己定义,不能是标签自带的属性 -->
<course type="free" type1="free" size="10">
<!-- <template slot-scope="scope">
{{scope}}
</template> -->
<!-- <template v-slot:header>
<h2>免费课程</h2>
</template> -->
<template v-slot:header="scope">
<h2>免费课程</h2>{{scope}}
<div v-for="item in scope.msg" :key="item">
{{item}}
</div>
</template>
<!-- <template v-slot:footer>
<h2>免费课程111111</h2>
</template> -->
</course>
<!-- <h2>精品课程</h2> -->
<course :type="type">
<template>
<h2>精品课程</h2>
</template>
</course>
<!-- <h2>折扣课程</h2> -->
<course type="discount">
<template>
<h2>折扣课程</h2>
</template>
</course>
</div>
子组件
<script>
Vue.component('course', {
template: '#course',
// 设置props属性就可以接受父组件传值
props: {
// 定义参数类型
type: [String],
type1: [String],
// 定义多个类型
// size: [String,Number],
// 默认值
size: {
// type 不能改
type: [String, Number, Object],
default: () => {
return {
name: 'zs'
}
}
}
},
data() {
return {
courseList: [],
msg: [1, 2, 3]
}
},
methods: {
getCourseList(type, pageSize, pageNum) {
let url = new URLSearchParams()
url.append('type', type)
url.append('pageSize', pageSize)
url.append('pageNum', pageNum)
return axios.post('http://wkt.shangyuninfo.cn/weChat/applet/course/list/type', url)
}
},
created() {
console.log(this.type);
console.log(this.type1);
console.log(this.size);
this.getCourseList(this.type, 5, 1).then(res => {
console.log(res);
this.courseList = res.data.rows
})
}
})
const vm = new Vue({
el: '#app',
data: {
type: 'boutique'
},
methods: {
}
})
</script>
3.兄弟组件之间传值
可以通过一个共同的父组件作为中介,将数据传递给兄弟组件。
4.跨级组件传值
可以通过provide和inject方法实现跨级组件之间的数据传递。
5.使用Vuex进行组件间通信
Vuex是Vue的状态管理工具,可以将数据存储在全局的store中,实现组件之间的通信。
总结
Vue组件传值可以让组件之间实现数据的共享和交互,从而实现更加灵活和高效的组件化开发,可以让我们更加方便地管理和维护Vue应用中的数据和事件,从而提高开发效率和代码质量。同时,组件传值也可以让我们更加灵活地组织应用的结构,从而实现更加复杂和高级的功能。