vue2组件通信

8/1/2022 vue

# 父>子

# 名字不能一样!!!

  • :father-msg="fatherKey"
  • Father.vue
    <Son
      :father-msg="fatherKey" 
    />
1
2
3
  • 直接props接收使用
  • son.vue
props: ['fatherMsg'],
1

# 子>父

  • 两种 1.函数参数 2. $emit发送 ($on) @ | v-on监听
  • Father.vue
    sonToFatherMethed(msg) {
      console.log(msg)
    },
    sonToFatherMethedEmit(emitMsg) {
      console.log(emitMsg)
    }
1
2
3
4
5
6

# 命名不能一样!!!

    <Son  
      :sonToFather="sonToFatherMethed"
      @sonToFatherEmit="sonToFatherMethedEmit"
    />
1
2
3
4
  • 子组件
  • son.vue
    props: ['sonToFather', 'sonToFatherEmit'],
    // methods
    tofather() {
        this.sonToFather('son-to-father-data')
    },
    tofatherEmit() {
        this.$emit('sonToFatherEmit', 'son-to-father-data-emit')
    }
1
2
3
4
5
6
7
8

# 非父子传值(全局状态可以vuex/pinia)

  • main.js 注册$bus
    window.$bus = new Vue;
1
  • brother1.vue
    // methods
    sendMsg() {
      $bus.$emit('send', '我是发过来的')
    },
1
2
3
4
  • brother2.vue
// mounted
    $bus.$on('send', (msg) => {
        this.msg = msg
        console.log(msg) // 我是发过来的
    });
1
2
3
4
5

# 父组件调用子组件内的方法(ref转发)

  • Father.vue
    <Son  
      ref="childRef" 
    />
1
2
3
      // 可以直接执行 this.$refs.child.sonMethod()
      // 如果报找不到sonMethod函数 加上this.$nextTick()延迟执行
      this.$nextTick(() => {
        this.$refs.childRef.sonMethod()
      })
1
2
3
4
5
  • Son.vue
    sonMethod() {
        console.log('sonMethod>>>>>>>>');
    }
1
2
3

# Vuex 使用

  • store/index.js
  • action 异步数据
  • mutations 计算数据
  • state 初始数据
  • getter 计算属性
//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//引用Vuex
Vue.use(Vuex)

const actions = {
    //响应组件中加的动作 commit相当于dispatch
	jia(context,value){
		context.commit('JIA',value)
	},
  getData({ commit, state }, value) {
      return new Promise((resolve, reject) => {
          resolve({
              name: 'tom',
              age: 18
          })
      })

  }
}

const mutations = {
    //执行加
	JIA(state, value){
		console.log('mutations中的JIA被调用了',state,value)
		state.sum += value
	}
}

//初始化数据
const state = {
   sum: 20
}

const getters = {
	bigSum(state){
		return state.sum * 10
	}
}

//创建并暴露store
export default new Vuex.Store({
	actions,
	mutations,
	state,
  getters,
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

# 使用vuex数据 (getter mutations action )

  • 使用map 然后用this访问
  import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
  methods: {
    ...mapActions(['getData']),
    ...mapMutations(['JIA']),
  }
1
2
3
4
5
  • 异步函数可以map 也可以dispatch
     //  ...mapActions(['getData']),
    this.getData('1112').then(res=> {
      console.log(22222222,res); // { name: 'tom', age: 18 }
    })
    // dispatch(type, payload)
    this.$store.dispatch('getData', '111').then(res => {
      console.log(22222222,res); // { name: 'tom', age: 18 }
    })
1
2
3
4
5
6
7
8

store的action

const actions = {
    getData({ commit, state }, payload) {
        
        return new Promise((resolve, reject) => {
            resolve({
                name: 'tom',
                age: 18
            })
        })

    }
}
1
2
3
4
5
6
7
8
9
10
11
12

# vuex模块化+命名空间

  • store/index.js
  • modules存放各个模块
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//引用Vuex
Vue.use(Vuex)

import test from './test'

//创建并暴露store
export default new Vuex.Store({
    state: {},
    mutations: {},
    actions: {},
    getters: {},
    modules: {
        test,
        // ...
    }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

test/index.js

const actions = {
    //响应组件中加的动作
	jia(context,value){
		context.commit('JIA',value)
	},
    getData({ commit, state }, value) {
        console.log('payload>>>>>>>>>>>>>>', value);
        return new Promise((resolve, reject) => {
            resolve({
                name: 'tom',
                age: 18
            })
        })

    }
}

const mutations = {
    //执行加
	JIA(state, value){
		console.log('mutations中的JIA被调用了',state,value)
		state.sum += value
	}
}

//初始化数据
const state = {
   sum: 20
}

const getters = {
	bigSum(state){
		return state.sum * 10
	}
}

//创建并暴露store
export default {
	actions,
	mutations,
	state,
    getters,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Last Updated: 8/1/2022, 4:25:42 AM