更新时间:2022-11-03 18:49:33
TL;DR 你可以在 node 中完美地使用 Vuex(没有浏览器),即使是单元测试.不过在内部,Vuex 仍然使用 Vue 的一些代码.
TL;DR you can perfectly use Vuex in node (without a browser), even for unit testing. Internally, though, Vuex still uses some code from Vue.
没有 Vue,你就不能使用 Vuex.因为:
You can't use Vuex without Vue. Because:
话虽如此,您确实需要 Vue,但您不需要 Vue 实例.您甚至不需要浏览器.
That being said, you do require Vue, but you don't require a Vue instance. You don't even require the browser.
所以是的,它在服务器端独立使用非常有用.
So yes, it is pretty usable in the server-side, standalone.
例如,您可以使用 Node.js 运行它,如下所示:
For instance, you could run it using Node.js as follows:
创建示例项目:
Create a sample project:
npm init -y
安装依赖项(注意:axios
不是必需的,我们只是为了这个演示添加它):
Install the dependencies (note: axios
is not necessary, we are adding it just for this demo):
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);
});
运行它:
Run it:
node index.js
它会输出:
It will output:
via regular getter: John
via method-style getter: JOHN
after commit: Charles
after fetch: Byron