vuex简单入门

vuex简单入门

vuex简单入门

需要先删除node_modules,然后使用cnpm install重新安装

然后 安装vuex   命令: cnpm install vuex --save-dev

vuex简单入门

 

要是使用vuex首先新建一个store.js文件,然后引用Vuex这个组件,然后定义state(定义组件管理或者公用的状态)和mutations(定义改变状态的方法)

store.js文件的代码:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state:{
        count:0
    },
    mutations:{
        increase(){
            this.state.count ++
        }
    },
    actions:{

    }
})

组件中如何使用vuex呢?

首先是引入store.js这个文件,然后再default里面对象去引用store,最后再组件中引用修改,使用到关键字 commit,store.commit("引用的方法")

组件info.vue使用store.js的代码:

<template>
    <div>
      info <button type="button" @click="add()">添加</button>
    </div>
</template>
<script>
// 在页面上使用vuex
import store from "@/store"
    export default {
       name:"info",
       store,
       methods:{
           add(){
               console.log("add enent from info")
               store.commit('increase')
            //  使用store.commit 引用store中的increase方法
           }
       }
    }
</script>

 

about.vue页面使用store.js的代码:

<template>
   <div>
       about
       <p>{{msg}}</p>
   </div>
</template>
<script>
// 引用store里面的状态
import store from "@/store"

    export default {
       name:"About",
       store,
       data(){
           return{
               msg:store.state.count
           }
       }
    }
</script>
<style scoped>
</style>

效果如下,info页面点击添加,about页面会显示对应数字。

vuex简单入门vuex简单入门

总结:

1、安装vuex

2、使用vuex

3、定义state(状态)、mutations(方法)

4、组件中引用store文件

5、default使用store

6、store.commit