vue state vuex使用

child.js
const child = {
  state: {
    isIframe: false,
  },
  mutations: {
    SET_ISIFRAME: (state, status) => {
      state.isIframe = status
    },
  },
  actions: {
    getIsiframe({ commit }, value) {
      commit('SET_ISIFRAME', value)
    },
  },
}

export default child

state.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state.js'
import * as getters from './getters'
import mutations from './mutations.js'
import actions from './actions.js'
import child from './modules/child.js'
Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production' // 开发环境中为true,否则为false
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
    child,
  },
  plugins: debug ? [createLogger()] : [], // 开发环境下显示vuex的状态修改
})

vue html

<script>
import { mapGetters } from 'vuex'

 data() {
    return { 
      isIframe: this.$store.state.child.isIframe,
    }
  },
 mounted() { 
    this.watchIframe()
  },
 methods:{
    // 监听父页面向子页面的传参
    watchIframe() {
      console.log(' this.isIframe: ', this.isIframe)
      window.addEventListener('message', (event) => {
        //此处执行事件
        console.log('监听父页面向子页面的传参', event.data)
        let data = event.data
        if (data.type == 'view') {
          this.isIframe = true
          this.$store.commit('SET_ISIFRAME', true)
        }
        console.log(' this.isIframe: ', this.isIframe)
      })
    },
    
 }

[转]

使用 vuex 修改 state 时,有两种方式:

可以直接使用 this.$store.state.变量 = xxx;
this.$store.dispatch(actionType, payload) 或者this.$store.commit(commitType, payload)
共同点:

能够修改state里的变量,并且是响应式的(能触发视图更新)
不同点:

若将 vue 创建 store 的时候传入 strict: true,开启严格模式,那么任何修改state的操作,只要不经过mutation的函数,vue就会报错。想详细了解报错原因,可以前往这里 。
调试工具无法查看修改记录
使用 dispatch 和 commit 的区别在于,前者是异步操作,后者是同步操作,所以一般情况下,推荐直接使用commit,
即 this.$store.commit(commitType, payload),以防异步操作会带来的延迟问题。

使用commit提交到mutation修改state的优点:

vuex 能够记录每一次state的变化记录,保存状态快照,实现时间漫游/回滚之类的操作。
————————————————
版权声明:本文为CSDN博主「Mr_linjw」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Mr_linjw/article/details/115455780

posted @ 2022-06-30 18:08  小小——开心  阅读(182)  评论(0编辑  收藏  举报