安装
yarn add vuex@next --save
yarn add es6-promise
code
main.js
这里注意,createApp是有返回值的,mount方法是没有的,所以先把app拿到之后,再做其他的一些挂载、引入操作,
这里利用createStore方法,创建了一个store,里面的state仅存在一个count的状态,然后定义了一个叫increment mutation, mutation里面定义着改变state的方法。之所以这样,因为store里面的state是无法从外部改变的。
import { createApp } from 'vue'
import App from './App.vue'
import { createStore } from 'vuex'
const store = createStore({
state(){
return {
count: 0
}
},
mutations: {
increment(state) {
state.count++;
}
},
});
const app = createApp(App);
app.use(store);
app.mount('#app');
app.vue
因为前面已经创建了store, 定义了一个叫increment 的mutation,在使用的时候,直接使用this.$store.commit('increment');利用store的commit方法,触发increment的执行。
<template>
<button @click="click">测试按钮</button>
</template>
<script>
export default {
name: 'App',
methods: {
click () {
this.$store.commit('increment');
console.log(this.$store.state.count)
},
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
![](https://img.haomeiwen.com/i2789632/91589cb4e2f6fc0d.png)
’
虽然vuex跟redux的工作目的类似,行为也类似,但是个人感觉vuex相对好上手一些。
网友评论