vue存取全局变量的方法(使用vuex的state实现)

本人的项目中,vue想存取全局变量,用到了vuex。

在此简要总结下。

(vuex的五个属性是:state、getters、mutations、actions和modules,这里先只总结用法)

一、vue存取全局变量的方法

1.从项目入口开始,本人的项目中,index.html附近,有个main.ts文件,内容如下:

import bootstrap from './bootstrap'

bootstrap('#app')

2.上面引入的bootstrap.ts中,有这样的代码:

import store from './store/index'

......

export default function mount(el: string) {
  return new Vue({
    store,
    router,
    render: h => h(App),
  }).$mount(el)
}

其中,重要的是引入了store,然后在new Vue里也写了({store})

3.这个引入的/store/index.ts中,是这样写的:

import Vue from 'vue'
import Vuex, { StoreOptions } from 'vuex'
import { RootState } from './types'

Vue.use(Vuex)

const store: StoreOptions<RootState> = {
  state: {
    version: '1.0.0',
    uploadUrl: ''
  },
  mutations: {
    "SET_UPLOADURL": function(state,url){
      state.uploadUrl = url
      console.log("保存上传url",url)
    }
  },
  getters: {
    "GET_UPLOADURL": function(state){
      console.log("返回上传url",state.uploadUrl)
      return state.uploadUrl
    }
  }
}

export default new Vuex.Store<RootState>(store)

其中,重要的是statemutationsgetters
state里的uploadUrl是可以存取的一个变量,先用这个举例子;
mutations是保存变量的方法,是个同步方法(如果要异步可以用actions,这里先不详细写了);
getters是读取变量的方法。

4.这里插入下types.ts,上面用到了,这个的内容如下:

export interface RootState {
  version: string,
  uploadUrl: string,
}

这个是上方StoreOptions<RootState>用到的,规定了state内变量的类型。

5.在vue的js部分中保存变量的方法:

this.$store.commit('SET_UPLOADURL','http://xxx.xxx.com/upload?filename=abc')

这个就可以把值存入state里的uploadUrl里。

6.在vue的js部分中读取变量的方法:

console.log(this.$store.getters.GET_UPLOADURL)

这样,就可以读取state里的uploadUrl,值就是刚才保存的http://xxx.xxx.com/upload?filename=abc

二、备注

1.由于new Vue({})的时候在全局声明了store,因此可以用this.$store执行方法

2.commitgetters应该是框架里的固定方法

3.存取时的SET_UPLOADURLGET_UPLOADURL,与申明mutationsgetters里的对应

猜你喜欢

转载自blog.csdn.net/BHSZZY/article/details/130089740