vuex是vue的状态管理包,通常在中大型项目中使用
①安装vuex
安装vuex的方法和安装其他包的方法一样,直接
npm install vuex --save
②使用vuex
在src的目录下创建store,然后再store目录下创建state.js文件
state.js文件内容如下
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increaseCount(state) {
state.count++;
}
}
})
state里面主要放的是一些我们需要存放的值
mutations主要是对state里面的属性进行修改
main.js文件内容如下
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuex from 'vuex' //引入vuex
import App from './App'
import router from './router'
import store from './store/state'
Vue.use(Vuex) //使用vuex
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store, //挂载vuex
router,
components: { App },
template: '<App/>'
})
main.js文件没有什么特别的地方,和其他包一样使用
测试组件index.vue文件内容如下
<template>
<div class="index">
<h1>count:{{count}}</h1>
<button @click="inscrse">增加</button>
</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
}
},
computed: {
count() {
return this.$store.state.count; //获取state里面的count属性
}
},
methods: {
inscrse() {
this.$store.commit('increaseCount'); //调取state.js文件中的increaseCount,使count++
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
这里出现了一些调用state属性和方法的使用方式,可以多多熟悉。
ps:使用vuex的话,建议安装一个Vue.js devtools的浏览器组件,可以帮助我们更直观的看到vuex的熟悉
我们安装的工具在开发者工具中有一个vue点击即可,我们可以看到刚刚使用的count属性
这里只对vuex做了一个简单的入门介绍,具体的可以多看一些视频和官方文档,进一步熟悉