Vue 组件间的通讯、传值方式 (vuex)
Vue 组件传值方式
父传子 | 子传父 | 非父子组件 | Vuex
一、父传子
父传子, 通过标签属性绑定,子组件通过 Props 监听获取标签属性数据变化
父组件:
<scroll-item :list-data='imageList' :has-data='hasData' />
子组件:
<script>
export default {
// 通过 props 接收
props: {
listData: {
type: Array,
default: null
},
hasData: {
type: Boolean,
default: false
}
}
}
</script>
二、子传父
子组件通过 $emit 发射一个数据方法,父组件通过 v-on 绑定事件 监听子组件方法
父组件:
<specile-head @head-BackBtn='acceptHead'/>
methods: {
acceptHead (val) {
console.log(val)
}
}
子组件:
<div @click='headBackBtn'> jensonhui </div>
methods: {
headBackBtn (item) {
this.$emit('head-BackBtn', item)
}
}
三、非父子组件
通过全局事件公交车BUS,创建新的Vue实例接收 发射
========================= 更新 vuex 封装使用 ===========================
根目录 src - store 文件夹下:
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import * as actions from './actions'
Vue.use(Vuex)
// 开发模式下使用
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
state: state,
mutations: mutations,
actions: actions,
modules: {},
strict: debug
})
state.js
const state = {
servers: 'developement',
userinfo: {}
}
export default state
muationtype.js
export const SET_USERINFO = 'SET_USERINFO'
export const SET_SERVERS = 'SET_SERVERS'
muations.js
import * as types from './mutationtype'
const mutations = {
[types.SET_USERINFO] (state, userinfo) {
state.userinfo = userinfo
},
[types.SET_SERVERS] (state, servers) {
state.servers = servers
}
}
export default mutations
actions.js
import * as types from './mutationtype'
export const setUserinfo = (context, list) => {
context.commit(types.SET_USERINFO, list)
}
export const setServers = (context, list) => {
context.commit(types.SET_SERVERS, list)
}
在页面中使用, home.vue
<template>
<div class="home">
<div>{{ userinfo }}</div>
<div>{{ servers }}</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: {
...mapState(['userinfo', 'servers'])
},
methods: {
...mapActions({
setUserinfo: 'setUserinfo',
setServers: 'setServers'
})
},
mounted () {
setTimeout(() => {
this.setUserinfo({
name: 'jensonhui',
age: 18
}),
this.setServers('product')
}, 1000)
}
}
</script>
文章目录
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。