VUE 组件间通信
- props
- this.$refs.子组件名称.edit()
- vue的自定义属性
- 消息订阅与发布(PubSub)
- vuex
1:props 父组件向子组件传值
父组件写法
<child :name="name" />
子组件写法
<script>
export default{
props:{
name: {
type: String,
default: ''
}
}
</script>
不支持兄弟组件,也不支持非子后代。
2: this.$refs.子组件名称.edit() 父组件向子组件传值
父组件写法
<child ref="childRef" />
// 写在想要触发传值的函数里
this.$refs.childRef.edit(this.name)
子组件写法
edit (e) {
// e为父组件传来的值
this.fatherData = e
}
3: 自定义事件 子组件向父组件传值
子组件写法
this.$emit('from-son', this.sonName)
父组件写法 父子组件的自定义事件(from-son)保持一致
<child @from-son="fromSon" />
// 事件触发
fromSon (data) {
// data就是子组件传来的值
console.log(data)
}
不支持隔代组件、兄弟组件 传值
4: 消息的订阅与发布(PubSubJs库)
下载安装
npm install --save pubsub-js
应用
import PubSub from 'pubsub-js'
// 发布(发送方):写在想要触发传值的操作里,比如button触发的click函数内
PubSub.publish('everything', this.myData)
// 订阅(接收方):
mounted () {
PubSub.subscribe('everything', (msg, comment) => {
// msg参数不能缺少,代表事件名,comment为接收到的数据
console.log(comment)
})
}
可以实现任意组件的通信,不受限制
5:vuex传值
将多次使用、多次进行相同运算的变量放置于vuex进行状态管理
一般写入四个文件:
index.js
mutation-typse.js
mutations.js
actions.js
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
Vue.use(Vuex)
// state存储想要全局使用的数据
const state = {
userInfo: null,
platformName: []
}
export default new Vuex.Store({
state,
actions,
mutations,
modules: {}
})
在组件中使用的方式
// 1. 从 vuex 中按需导入 mapState 函数
import { mapState } from 'vuex'
// 2. 将全局数据,映射为当前组件的计算属性, 必须是计算属性内
computed: {
...mapState(['platformName'])
}
mutation-types.js
export const SET_USER_INFO = 'SET_USER_INFO'
export const GET_UPPER_PLATFORM = 'GET_UPPER_PLATFORM'
mutations.js
只进行一些赋值操作,直接更新state的值,不能写入异步代码;
谁来触发:被actions的commit('mutation名称')触发
import * as types from './mutation-types'
export default {
[types.SET_USER_INFO] (state, userInfo) {
state.userInfo = userInfo
},
[types.GET_UPPER_PLATFORM] (state, { data }) {
state.platformName = data
}
}
actions.js
可写入异步代码;
谁来执行:通过使用commit()触发mutation的调用,间接更新state的值;
谁来触发:组件中:$store.dispatch('actions名称',data)——data为可能需要的参数
import { getUpperPlatform } from '@/api/face'
import * as types from './mutation-types'
export default {
async getUpperPlatformS ({ commit }) {
await getUpperPlatform().then(res => {
const data = res.data
// commit(types.GET_UPPER_PLATFORM, { data })的data想要和mutations.js的形参名称保持一致
commit(types.GET_UPPER_PLATFORM, { data })
}).catch(e => {
console.log(e)
})
}
}
组件中使用
import { mapState, mapActions } from 'vuex'
// 映射为当前组件的方法
mothods :{
...mapActions([
'getUpperPlatformS'
]),
// 或者采用第二种方式
getUpperPlatformS (){
this.$store.dispatch('getUpperPlatformS')
}
}
// 调用该方法
created () {
this.getUpperPlatformS()
}
// 得到调用getUpperPlatformS后,更新过的platformName,并在computed计算属性中映射为组件内变量
computed: {
...mapState(['platformName'])
},
// 或者在想要操作的地方直接取值,不用计算属性
this.$store.state.platformName
优点在于如果一个值始终是由调用一个异步函数而得到,并且多个页面得到这个值,
那么可在第一次使用到这个函数的时候调用依次异步函数,并将得到的值存储在vuex的state内,其他页面使用时,直接取值即可。
避免多次请求。

浙公网安备 33010602011771号