除了《Vuex最基本样例》中的方法外,还有两种方法访问状态对象state:html
只须要改app.vue文件vue
方法一:引入computedweb
<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>
方法二:在方法一基础上引入mapStatevuex
<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写法app
<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>
运行结果以下:post
看出来,结果是同样的。this