温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vuex的热更替的实现方法

发布时间:2020-07-18 14:00:58 来源:亿速云 阅读:133 作者:小猪 栏目:web开发

这篇文章主要讲解了Vuex的热更替的实现方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

前言

我们在使用Vuex的时候,会时不时的更改Vuex内的数据,但是页面不会随之更新,如果数据量大,一个数据依赖另一个数据的话,这样我们要是再刷新页面的话会把以前依赖的数据清空,效率特别低。所以,今天我总结了怎么实现Vuex热更替的功能。

实现

首先,我们这里使用了Vue CLI3。在根目录下的src目录下我们有一个存放Vuex的文件夹叫做store文件夹。首先我们分割成几个模块。

Vuex的热更替的实现方法

下面我们把它们分别引入,这里没有分割actions,不过与其他属性同理,这里有不做介绍。下面我们在index.js编辑下面代码:

import Vuex from 'vuex'
// 引入分割的模块
import state from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'

export default ()=>{
// 这里需要赋给一个store变量
 const store = new Vuex.Store({
  state:state,
  mutations:mutations,
  getters:getters
 })
 // 热更新模块
 if(module.hot){
 // 跟上面一样,写入对应的分割模块路径
  module.hot.accept([
   './state/state',
   './mutations/mutations',
   './getters/getters'
  ],()=>{
  // 开启热更替
   const newState = require('./state/state').default
   const newMutations = require('./mutations/mutations').default
   const newGetters = require('./getters/getters').default
   store.hotUpdate({
    state:newState,
    mutations:newMutations,
    getters:newGetters
   })
  })
 }
 
 return store
}

我们还需要在main.js修改:

import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
import createStore from './store/index.js'

Vue.config.productionTip = false

Vue.use(Vuex)
const store=createStore();

new Vue({
 store,
 render: h => h(App)
}).$mount('#app')

一些其他api

// store.registerModule({ //动态添加模块
// })

// 相当于getter
// store.watch((state)=>state.count+1,(newCount)=>{
//  console.log('new count watched , '+newCount)
// })

// mutation被调用时
// store.subscribe((mutation,state)=>{
//  console.log(mutation.type)
//  console.log(mutation.payload)
// })

// action被调用时
// store.subscribeAction((action,state)=>{
//  console.log(action.type)
//  console.log(action.payload)
// }) 

看完上述内容,是不是对Vuex的热更替的实现方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI