vuex的使用方法
npm install vuex -s
在src下创建store,文件夹下创建index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state:{
count: 0
},
getters:{
},
mutations:{
increment (state) {
state.count++
},
remove (state) {
state.count--
}
//同步操作,写法:this.$store.commit('mutations方法名',值)
},
actions:{
increment (context) {
context.commit('increment')
}
//含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
}
});
export default store;
在组件获取vuex的数据
<template>
<div class="hello">
<h1>{
{ msg }}</h1>
<h2>{
{this.$store.state.count}}</h2>
<h2>{
{count1}}</h2>
<div ref="getText">Add "scoped" attribute to limit CSS to this component only</div>
<!-- <button @click="dome">获取ref属性</button> -->
<button @click="increment">vuex加</button>
<button @click="remove">vuex减</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
computed:{
...mapState({
count1: state=>state.count * 88
}),
// ...mapMutations([
// 'increment',
// 'remove'
// ])
},
methods: {
dome () {
console.log(this.$refs.getText)
/* eslint-disable */
},
...mapMutations([ //this.$store.commit简写方法
'increment',
'remove'
]),
...mapActions([
'increment', // map `this.increment()` to `this.$store.dispatch('increment')`
//含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
]),
// increment() {
// let n = 2;
// this.$store.commit('increment',n)//同步操作,写法:this.$store.commit('mutations方法名',值)
// console.log(this.$store.state.count,n)
// },
// remove () {
// this.$store.commit('remove')//同步操作,写法:this.$store.commit('mutations方法名',值)
// }
}
}
</script>
<style scoped>
</style>
还没有评论,来说两句吧...