本文讲解
4.17 vuex的其本使用8步骤:
目录
vuex的基本使用第1步:在/store/index.js里面设置数量count.
vuex的基本使用第2步:在About.vue里面设置计算属性的值。
vuex的基本使用第3步:在About.vue里面设置显示count。
vuex的基本使用第4步:在About.vue里面设置+1按钮
vuex的基本使用第5步:在About.vue里面设置声明increment方法
vuex的基本使用第6步:在/store/index.js里面设置Increment方法
vuex的基本使用第7步:在/store/index.js里面设置修改状态。
vuex的基本使用第8步:在App.vue上设置使用。
首先通过vue create vuex新建一个vuex项目,项目目录如下:
每一步操作,在其相应的代码里面都有备注。
第1步:在/store/index.js里面设置数量count.
index.js代码:
// store/index.js内容
import Vue from 'vue'
//1.导入模块
import Vuex from 'vuex'
//2.使用当前的插件
Vue.use(Vuex)
const store = new Vuex.Store({
state: { //当前的状态
count:0 //vuex的基本使用第一步:设置数量count.
},
getters: { //store的计算属性
},
mutations: { //声明同步的方法
increment(state){ //vuex的基本使用第七步:修改状态。
//修改状态
state.count++
},
decrement(state){
state.count--
}
},
actions: { //声明异步的方法
// increment({commit}){ //vuex的基本使用第六步:声明Increment方法
// //commit mutations中声明的方法
// commit('increment')
// },
// decrement({commit}){
// commit('decrement')
// }
},
modules: {
}
})
export default store;
//4.17 vuex的其本使用8步骤:
//vuex的基本使用第1步:在/store/index.js里面设置数量count.
//vuex的基本使用第2步:在About.vue里面设置计算属性的值。
//vuex的基本使用第3步:在About.vue里面设置显示count。
//vuex的基本使用第4步:在About.vue里面设置+1按钮
//vuex的基本使用第5步:在About.vue里面设置声明increment方法
//vuex的基本使用第6步:在/store/index.js里面设置Increment方法
//vuex的基本使用第7步:在/store/index.js里面设置修改状态。
//vuex的基本使用第8步:在App.vue上设置使用。
第2步:在About.vue里面设置计算属性的值。
第3步:在About.vue里面设置显示count。
第4步:在About.vue里面设置+1按钮。
第5步:在About.vue里面设置声明increment方法。
// About.vue内容
<template>
<div class="about">
<h1>This is an about page</h1>
{{count}} <!-- //vuex的基本使用第三步:显示count -->
<button @click="increment">+1</button> <!-- //vuex的基本使用第四步:设置+1按钮 -->
<button @click="decrement">-1</button>
</div>
</template>
<script>
export default{
computed: { //vuex的基本使用第二步:设置计算属性的值。
count() {
return this.$store.state.count //获取count值。实时监听count的变化。
}
},
methods:{ //vuex的基本使用第五步:声明increment方法
increment(){
//dispatch触发actions中声明的方法
// this.$store.dispatch('increment');
this.$store.commit('increment');
},
decrement(){
// this.$store.dispatch('decrement');
this.$store.commit('decrement');
}
}
}
</script>
第6步:在/store/index.js里面设置Increment方法
第7步:在/store/index.js里面设置修改状态。
请查看上面的index.js代码。
第8步:在App.vue上设置使用。
App.vue代码:
// App.vue内容。
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
{{$store.state.count}} <!-- //vuex的基本使用第八步:在App.vue上使用。 -->
</nav>
<router-view/>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
}
nav a {
font-weight: bold;
color: #2c3e50;
}
nav a.router-link-exact-active {
color: #42b983;
}
</style>
运行结果: