Vuex的官网链接https://vuex.vuejs.org/zh/
vuex也是插件,需要安装
npm install vuex --save
// 1.提取出一个公共的store对象,用于保存在多个组件中共享的状态
//2.将store对象放置在new Vue对象中,这样可以保证在所有的组件中都可以使用到
//3.在其他组件中使用store对象中保存的状态即可
//通过this.$store.state.属性的方式来访问状态
//通过this.$store.commit('mutation中方法')来修改状态
创建store目录,下面建一个index.js。
- 安装插件
- 创建对象
- 导出
state、mutations、actions 、getters 、modules都是方法
然后在main.js中导入:
在APP.vue中写:
<template>
<div id="app">
<h2>{{ message }}</h2>
<h2>{{ $store.state.counter }}</h2>
<button @click="addition">+</button>
<button @click="subtraction">-</button>
<h2>HELLO VUE内容</h2>
<hello-vuex ></hello-vuex>
</div>
</template>
<script>
import HelloVuex from './components/HelloVuex.vue'
export default {
name: 'app',
components:{
HelloVuex
},
data(){
return{
message:'我是APP的内容',
}
},
methods:{
addition(){
this.$store.commit('increment')
},
subtraction(){
this.$store.commit('decrement')
}
}
}
</script>
<style>
</style>
在components目录下建HelloVuex.js
<template>
<div>
<h2>{{ $store.state.counter }}</h2>
</div>
</template>
<script>
export default {
name:"HelloVuex",
}
</script>
<style>
</style>
在index.js中:
import Vue from 'vue'
import Vuex from 'vuex'
//1安装插件
Vue.use(Vuex)
//2创建对象
const store = new Vuex.Store({
state:{
counter:100
},
mutations:{
increment(state){
state.counter++
},
decrement(state){
state.counter--
}
},
actions:{
},
getters:{
},
modules:{
}
})
export default store
效果图
如果要修改state中的内容,要通过mutations进行修改,安装插件Devtools可对修改的内容进行监听,当有异步操作时要使用actions。具体可到官方网站查看。
我还没学会那。