新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Vuex的热更替的实现方法

这篇文章主要讲解了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的热更替的实现方法有进一步的了解,如果还想学习更多内容,欢迎关注创新互联行业资讯频道。


新闻名称:Vuex的热更替的实现方法
文章出自:http://www.wjwzjz.com/article/goeigp.html
在线咨询
服务热线
服务热线:028-86922220
TOP