除了《Vuex最基本样例》中的方法外,还有两种方法访问状态对象state:
只需要改app.vue文件
方法一:引入computed
<template> <div id="app"> <p>hello vuex</p> <p>{{$store.state.count}}</p> <p>{{count1}}</p> <button @click = "$store.commit('add')">+</button> <button @click = "$store.commit('reduce')">-</button> </div> </template> <script> export default { name: 'App', data(){ return { count: 1 } }, computed:{ count1(){ return this.$store.state.count+1 } } } </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>
方法二:在方法一基础上引入mapState
<template> <div id="app"> <p>hello vuex</p> <p>{{$store.state.count}}</p> <p>{{count1}}</p> <button @click = "$store.commit('add')">+</button> <button @click = "$store.commit('reduce')">-</button> </div> </template> <script> import { mapState } from 'vuex' //注意这里 export default { name: 'App', data(){ return { count: 1 } }, computed: mapState({ count1: state=>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>
方法三:简化的mapState写法
<template> <div id="app"> <p>hello vuex</p> <p>{{$store.state.count}}</p> <p>{{count}}</p> //这里是count就行 <button @click = "$store.commit('add')">+</button> <button @click = "$store.commit('reduce')">-</button> </div> </template> <script> import { mapState } from 'vuex' export default { name: 'App', // data(){ //这里要注释掉data里的count,否则不生效,不知道原因。这点和视频教程不太一样 // return { // count: 1 // } // }, computed: mapState([ '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>
运行结果如下:
看出来,结果是一样的。