Vuex的简单使用
一丶个人理解:vuex相对于来说是一个存储空间,也就是说它相当于一个大仓库,里面放的是我们的数据.
二丶我觉得有一个地方用vuex就非常的适合,就是在我们进行组件传值的时候,比如说父子传值,单个的父子传值用一个props来接受很简单,但是你要是给你子的儿子(父亲的孙子),以此类推传值的时候,我们总不能一直用props去一个一个接收吧,这时候就可以用到vuex来传递我们需要的数据了,下面是做了一个简单的加减的操作,不多说了,直接上代码.
1 <template> 2 <div class="home"> 3 <!-- {{this.$store.state.count}} --> 4 <!-- 这里的count1是从index.js里面的state里面拿出来的 --> 5 {{count1}} 6 <button @click="add(1)">+</button> 7 <button @click="jian">-</button> 8 </div> 9 </template> 10 11 <script> 12 //引入辅助函数 13 import {mapState,mapActions} from "vuex" 14 export default { 15 data(){ 16 return{ 17 18 } 19 }, 20 computed:{ 21 // count1(){ 22 // return this.$store.state.count 23 // } 24 ...mapState({ 25 count1:state=>state.count 26 }) 27 }, 28 methods:{ 29 ...mapActions([ 30 'add', 31 'jian' 32 ]) 33 } 34 } 35 </script>
三丶在Vue的项目中有一个store的文件夹,打开它,找到index.js文件,下面是代码.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:1
},
mutations: {
add(state,a){
state.count++;
console.log(a)
},
jian(state)
{
if(state.count>1)
{
state.count--
}
}
},
actions: {
add(context,a){
context.commit("add",a)
},
jian(context){
context.commit("jian")
}
},
modules: {
}
})
//总结 actions用来操作mutations 然后再通过mutations来操作state
注: 代码1中{{ this.$store.state.count}} 这个是直接就可以再页面中获取到我们存储在store里面的index.js里面的count数据;一般不常用这个方法.
浙公网安备 33010602011771号