在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的存值,加上元件傳值,真的敲好用~