首页 > 语言 > JavaScript > 正文

详解vuex 渐进式教程实例代码

2024-05-06 15:27:43
字体:
来源:转载
供稿:网友

vuex 渐进式教程,从入门级带你慢慢深入使用vuex。

Vuex 是什么?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态, 并以相应 的规则保证状态以一种可预测的方式发生变化。

vuex官网: vuex.vuejs.org/zh/guide/

安装

安装vue-cli:

cnpm install -g vue-cli vue init webpack vuex

安装vuex

cnpm i vuex --save

1.初级使用方法

// main.jsimport Vue from 'vue'import App from './App'import router from './router'import Vuex from 'vuex' // 引入vuexVue.config.productionTip = falseVue.use(Vuex);let store = new Vuex.Store({ // store 对象 state:{  count:0 }})/* eslint-disable no-new */new Vue({ el: '#app', router, store, //使用store,这可以把 store 的实例注入所有的子组件 components: { App }, template: '<App/>'})

此时可以在组件中使用 this.$store.state.count 获取store中state的值。如:

// 在组件的computed中使用 computed:{   count(){   return this.$store.state.count;   } }

想想一下当项目比较大的时候数据繁琐,如果按照上述方法使用vuex,当你打开main.js你看的到场景是比较混乱的,各种数据繁杂在一起,不便于日后的维护。请看下一步:

2.中级使用方法: modules 模块化

state用法

2.1 在main.js中删除下述这部分代码

let store = new Vuex.Store({ // store 对象 state:{  count:0 }})

2.2. 在src目录下新建store文件夹并在该文件夹下新建index.js文件。 在 store/index.js写入:

import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({ strict:true, // 开启严格模式 确保state 中的数据只能 mutations 修改 state:{  count:0 }})export default store;

对应的main.js应该写入:

import store from './store'

写到这里,我们在组件里就可以获取到store里的state的值了

2.3 为了方便测试直接在HelloWorld.vue 中使用store

<template> <div class="hello">  <h2>{{count}}</h2> </div></template><script>export default { name: 'HelloWorld', computed:{   count(){    return this.$store.state.count;   } }}</script>

很多时候咱们要对state里的值进行操作,在vuex提供了一个方法mutations

mutations用法(使用mutations可以修改state的值)

在sore/index.js写入:

//... state:{  count:0 }, mutations:{ // 更改数据的方法  add(state){   state.count++  },  //提交载荷用法//   add(state,n){ //   state.count += n//  },  sub(state){   state.count--  } }...//            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选