import { mapState } from 'vuex'
...mapState(['count'])
3.添加到组件
<template> <div> <h1>count值:{{count}}</h1> </div> </template> <script> import { mapState } from 'vuex' export default { data() { return {} }, computed: { ...mapState(['count']) } } </script>
import { mapMutations } from 'vuex'
methods: { ...mapMutations(['add']) }
3.在methods使用
methods: { ...mapMutations(['add']), changeEvent(){ this.add(5); } }
import { mapActions } from 'vuex'
<template> <div class="content"> <div>当前最新count值:{{count}}</div> <div>getters: {{showNum}}</div> <button @click="changeEvent">触发按钮</button> </div> </template> <script> import { mapState,mapActions} from 'vuex'; export default { name: 'Content', methods: { ...mapActions(['addAsync']), // 调用dispatch触发actions时携带参数 changeEvent2() { this.addAsync(5); }, }, computed: { ...mapState(['count']), } } </script>
<template> <div class="content"> <img alt="Vue logo" src="../assets/logo.png"> <div>当前最新count值:{{count}}</div> <div>getters: {{showNum}}</div> <button @click="changeEvent1">触发同步按钮</button> <button @click="changeEvent2">触发异步按钮</button> </div> </template> <script> import { mapState,mapMutations, mapActions, mapGetters} from 'vuex'; export default { name: 'Content', methods: { ...mapMutations(['add']), ...mapActions(['addAsync']), changeEvent1(){ this.add(5); }, // 调用dispatch触发actions时携带参数 changeEvent2() { this.addAsync(5); }, }, computed: { ...mapState(['count']), ...mapGetters(['showNum']) } } </script>