在vue项目中,组件之间的传值是非常常用且重要的,本文主要介绍一下各种组件之间的传值方式
1.父组件向子组件传值
父组件: fatherPage.vue
<template>
<!-- 引入子组件 -->
<add-course :classCourseName="classCourseName"></add-course>
</template>
<script>
import addCourse from './addCourse'
export default {
name: 'index',
data() {
return {
}
},
components: {
addCourse
}
}
</script>复制代码
子组件addCourse.vue
<template>
<div class="up_load_dialog">
<span>{{classCourseName}}</span>
</div>
</template>
<script>
export default {
name: 'addCourseIndex',
props: {
//从父组件接收值
classCourseName: {
type: String,
default: ()=>{
return ''
}
}
},
data(){
return {
}
}
}
</script>复制代码
2.子组件向父组件传值
子组件addCourse.vue
<template>
<div class="up_load_dialog">
<span @click="setNewCourse"></span>
</div>
</template>
<script>
export default {
data(){
return {
childName: '我是子组件的数据'
}
},
methods: {
setNewCourse() {
//通过emit的getValue方法将值childName传给父组件
this.$emit('getValue', this.childName)
}
}
}
</script>复制代码
父组件fatherPage.vue
<template>
<add-course @getValue="getValue"></add-course>
</template>
<script>
export default {
data(){
return {
name: ''
}
},
methods: {
getValue(value) {
this.name = value
alert("成功接收到子组件传来的值")
}
}
}
</script>复制代码
3.非父子组件之间传值
公共组件在config中加入event-bus.js
import Vue from 'vue'
let eventBus = new Vue();
eventBus.install = function (vue, options) {
Vue.prototype.$eventBus = Vue.eventBus = eventBus;
}
export default eventBus复制代码
在main.js中引入event-bus.js
const Vue = require('vue')
import router from './router'
import store from './store'
const Vuetify = require('vuetify')
import 'material-design-icons-iconfont'
import '../src/assets/css/base.css'
import ajax from './config/fetch.js'
import './config/filters.js'
import './config/directives'
import api from './config/api/index'
const echarts = require('echarts/lib/echarts')
import common from './config/common'
import EventBus from './config/event-bus.js'
...
Vue.use(EventBus);复制代码
如果不想用以上的方式,也可以建一个eventBus.js,然后在每个需要用到的页面引入该文件也可以
传值的particialAnalysis.vue
<template>
<div class="edit-partial-analysis">
<div class="edit-score-title clear">
<h3>偏科分析</h3>
<div class="edit-score-button">
<span class="edit-score-button-save" @click="saveScorePage">保存</span>
</div>
</div>
</template>
<script>
export default {
name: 'editPartialAnalysis',
data() {
return {
number: ''
}
},
methods: {
// 保存设置的分数段
saveScorePage() {
this.$eventBus.$emit('editParamsButton', false); //传给兄弟editModule,告知隐藏设置参数页面
},
}
}
</script>复制代码
接收值的editModule.vue
<template>
<div class="score-analysis-con-one" :class="{hideSetAndParams: editParamsHideButton == true}">
<span v-if="editParamsHideButton">接收eventBus传过来的值</span>
</div>
</template> 复制代码
<script>
export default {
name: 'index',
data() {
return {
editParamsHideButton: true,
}
},
mounted() {
//设置参数页面点击返回隐藏设置参数的页面
this.$eventBus.$on('editParamsButton',(data)=>{
this.editParamsHideButton = data;
})
},
}
</script>复制代码
差不多就这样了,下次再写一下vuex的存值,加上组件传值,真的敲好用~