【问题标题】:Is it possible to use Vuex without Vue? (Vuex server-side?)是否可以在没有 Vue 的情况下使用 Vuex? (Vuex 服务器端?)
【发布时间】:2018-09-15 23:40:58
【问题描述】:

Vuex 抱怨如果不调用 Vue.use(Vuex) 就无法创建新的 store 实例。虽然这通常没问题,但我正在摆弄使用同一个商店编写后端/前端的想法。有人知道答案吗?

谢谢。

【问题讨论】:

    标签: javascript node.js vue.js vuex


    【解决方案1】:

    TL;DR 你可以在节点中完美地使用 Vuex(无需浏览器),甚至用于单元测试。不过,在内部,Vuex 仍然使用 Vue 的一些代码。

    没有 Vue 就不能使用 Vuex。因为:

    话虽如此,您确实需要 Vue,但您不需要 Vue 实例。你甚至不需要浏览器。

    所以是的,它在服务器端非常有用,独立。

    例如,您可以使用 Node.js 运行它,如下所示:

    • 创建一个示例项目:

      npm init -y
      
    • 安装依赖(注意:axios 不是必需的,我们只是为了这个演示添加它):

      npm install --save vue vuex axios
      
    • 创建一个脚本(index.js):

      const axios = require('axios');
      const Vue = require('vue');
      const Vuex = require('vuex');
      Vue.use(Vuex);
      
      const store = new Vuex.Store({
        strict: true,
        state: {name: "John"},
        mutations: {
          changeName(state, data) {
              state.name = data
          }
        },
        actions: {
          fetchRandomName({ commit }) {
            let randomId = Math.floor(Math.random() * 12) + 1  ;
            return axios.get("https://reqres.in/api/users/" + randomId).then(response => {
              commit('changeName', response.data.data.first_name)
            })
          }
        },
        getters: {
          getName: state => state.name,
          getTransformedName: (state) => (upperOrLower) => {
            return upperOrLower ? state.name.toUpperCase() : state.name.toLowerCase()
          }
        }
      });
      console.log('via regular getter:', store.getters.getName);
      console.log('via method-style getter:', store.getters.getTransformedName(true));
      
      store.commit('changeName', 'Charles');
      console.log('after commit:', store.getters.getName);
      
      store.dispatch('fetchRandomName').then(() => {
          console.log('after fetch:', store.getters.getName);
      });
      
    • 运行它:

      node index.js
      
    • 它会输出:

      via regular getter: John
      via method-style getter: JOHN
      after commit: Charles
      after fetch: Byron
      

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 2020-02-16
      • 2022-06-24
      • 2013-01-03
      • 2019-01-09
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 2021-03-02
      相关资源
      最近更新 更多