vuex其实挺好用的,页面之间不需要来回传值了,特别是写工作系统的时候,数据总是倒来倒去,之前vuex里的模块都是零零散散的在用,最近写的一个项目中几乎全都用上了,写个总结,以便以后参考!
1、首先需要的是在项目中安装,在Vuex的官网中提供了三种安装方式
页面:
<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>
NPM:
npm install vuex --save
Yarn:
yarn add vuex
2、在mian.js中定义vuex的每一个模块
import App from './App'
import router from './router'
import Vuex from 'vuex'
Vue.config.productionTip = false
//注册vuex
Vue.use(Vuex)
const store = new Vuex.Store({ // 这里注意S要大写不然会报错
//定义变量
state: {
num: 12
},
// 定义方法
mutations: {
addnum(state, val) {
state.num += val
},
accnum (state, val) {
state.num *= val
}
},
// 修饰变量
getters: {
getnum(state){
return '数值为:'+ state.num
}
},
// 复杂的或多个的方法同时使用
actions: {
goingNum (context, val) {
context.commit('addnum', val)
context.commit('accnum', val)
}
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, // store需要定义进来
components: { App },
template: '<App/>'
})
3、在业务页面使用定义好的变量和方法,通过传参来动态添加数据
<div class="hello">
<h2>{{num}}</h2>
<h3>{{getnum}}</h3>
<button @click="inNum">+</button>
<button @click="goingisnum">GO</button>
</div>
</template>
<script>
import {mapState , mapMutations, mapGetters, mapActions} from 'vuex' // 引入vuex的方法
export default {
name: 'HelloWorld',
computed: {
// 映射出store中的变量,无需在data中定义,可以直接使用
...mapState(['num']),
...mapGetters(['getnum'])
},
data () {
return {
value: 188,
val: 10
}
},
methods: {
// 映射store中的方法
...mapMutations(['addnum']),
...mapActions(['goingNum']),
// 使用方法,并用传参的方式动态添加数据
goingisnum () {
this.goingNum(this.val) // this.value就是本页面定义的参数
},
inNum () {
this.$store.commit('addnum', this.value) // this.value就是本页面定义的参数
}
}
}
</script>
结果:
a、mian.js的原值num为12,本页面定义val为10,点击加号,调用addnum方法,数值为22
![](https://img.haomeiwen.com/i5906612/0e48a61b137e12a7.png)
b、mian.js的原值num为12,本页面定义val为10,点击GO后,调用goingNum方法,执行加再执行乘,数值为220
![](https://img.haomeiwen.com/i5906612/4b72f96b540c5b61.png)
4、modules模块的用法
数据较多的时候,我们会把vuex里的数据分成多个文件,在每个文件集合里单独定义:state、mutations、 getters、actions,这样所有的数据就不再需要定义在一个store中,没有相关性的数据就解耦了,方便项目管理和维护。
a、首先新建文件夹src>sotre>modules,新建文件:modules>modules.js和 store>index.js
![](https://img.haomeiwen.com/i5906612/8458a71048784abf.png)
b、在main.js中引入整个store文件
import App from './App'
import router from './router'
import Vuex from 'vuex'
import store from './stort' // 引入文件
Vue.config.productionTip = false
Vue.use(Vuex)
new Vue({
el: '#app',
router,
store, // 引入完成需要注册一下
components: { App },
template: '<App/>'
})
c、在index.js中注册所有的文件集合
import Vue from 'vue'
import Vuex from 'vuex'
import mustbe from './modules/mustbe.js' // 将文件引入store中
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
mustbe // 注册到store中
}
})
d、新建的文件中写入需要定义模块
const mustbe = {
// 创建state模块
state: {
mustValue: 'i did it'
}
}
export default mustbe
e、最后在逻辑页面拿到数据
data () {
return {
mustValue: this.$store.state.mustbe.mustValue
}
}
网友评论