Vuex 安装步骤包括:安装 Vuex 依赖项 npm install vuex --save。创建 Vuex 存储,在 src 目录建立 store.js 文件并导入、使用 Vuex。在 Vue 实例中注入 Vuex 存储,在 main.js 文件中导入并使用 store。在组件中使用 Vuex,使用 mapState、mapMutations 和 mapActions 辅助函数映射状态、突变和动作到组件。

如何安装 Vuex
步骤:
1. 安装 Vuex
<code class="bash">npm install vuex --save</code>
2. 创建 Vuex 存储
立即学习“前端免费学习笔记(深入)”;
在 src 目录下创建一个名为 store.js 的文件:
<code class="javascript">import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
// 你的状态对象
},
mutations: {
// 你的突变对象
},
actions: {
// 你的动作对象
},
getters: {
// 你的获取器对象
}
})
export default store</code>3. 在 Vue 实例中注入 Vuex 存储
在 main.js 文件中:
<code class="javascript">import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')</code>4. 在组件中使用 Vuex
mapState 辅助函数将 Vuex 状态映射到组件数据:<code class="javascript">import { mapState } from 'vuex'
export default {
computed: {
...mapState([
'stateVariable1',
'stateVariable2'
])
}
}</code>mapMutations 辅助函数将 Vuex 突变映射到组件方法:<code class="javascript">import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations([
'mutation1',
'mutation2'
])
}
}</code>mapActions 辅助函数将 Vuex 动作映射到组件方法:<code class="javascript">import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([
'action1',
'action2'
])
}
}</code>以上就是vue2怎么安装vuex的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号