Vuex的使用

准备工作:
1、使用vue-cli脚手架搭建一个vue项目(vue-demo)。
2、component文件夹下新建2个组件A和B。配置好路由。
Vuex的使用

//index.js文件配置好路由
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import ComponentA from '@/components/ComponentA'
import ComponentB from '@/components/ComponentB'
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      children:[
        {
          path:"/a",
          name:"ComponentA",
          component:ComponentA
        },
        {
          path:"/b",
          name:"ComponentB",
          component:ComponentB
        }
      ]
    }
  ]
})

helloword文件加两个按钮:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>  
    <button @click="comA">组件A</button>
    <button @click="comB">组件B</button>
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
   methods:{
    comA(){
        this.$router.push('/a')
    },
    comB(){
        this.$router.push('/b')
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

Vuex的使用

Vuex的使用

Vuex相当于vue项目的一个公共的数据存放仓库。vuex文档

安装vuex

 cnpm install vuex --save

项目中引用

1、src下创建一个文件夹store,文件夹里新建index.js文件。
Vuex的使用

//index.js文件
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex);

//创建store对象
const store = new Vuex.Store({
    state
})
//定义状态
var state = {
    num:1
}
export default store;

main.js中引用

Vuex的使用

组件中使用

有两种方式:
1、页面中通过$store.state.num
2、计算属性中使用
Vuex的使用
效果
Vuex的使用
组件中使用方式一样:
Vuex的使用

改变num 的值

需要通过mutation来实现。
在组件A中添加一个按钮,点击时使num的值+1;

//组件A
<template>
    <div>
        这里是组件A:
        {{$store.state.num}}
        <!-- 通过commit方法来实现 ‘add’是mutation中方法 -->
        <button @click="$store.commit('add')">num+1</button>  
    </div>
</template>
<script>
    export default {
        name: 'ComponentA',  
    }
</script>

对应的index.js文件需要增加mutations的代码

//改变状态
var mutations = {
    add(state){
        state.num++
    }
}
//创建store对象
const store = new Vuex.Store({
    state,
    mutations
})

Vuex的使用
当状态改变的操作较多,或者在改变状态前需要做一些判断之类的其他操作。就要用到Action了。
我们在组件B中添加一个按钮,让num的值减1,当num的小于等于1时 ,就不能减了。

//组件B
<template>
    <div>
        这里是组件B
        <button @click="$store.dispatch('jian')">num--</button>
    </div>
</template>
<script>

    export default {
        name: 'ComponentB', 
    }
</script>

index.js文件添加actions
Vuex的使用
至此,我们可以用vuex来对数据进行存储、操作等。

其他的情况

如果某一个状态跟其他的状态有关联,即这个状态的值依赖其他状态的值。我们需要使用getter(相当于组件中的计算属性)来操作。
index.js文件中添加getters.
Vuex的使用
在HelloWorld组件中使用:
Vuex的使用
当num的值改变时,count的值也会随之改变

Vuex的使用
上面的mapGetters是vuex提供的辅助函数。其他的还有mapState、mapActions、mapMutations 用法和mapGetters一样。