如何在Vue项目中使用Vuex

在一个vue项目中使用vuex,需要根据项目来源分两种情况 :

第一种情况:在老项目中使用。 先额外安装vuex包,然后在配置。

第二种情况:在新项目中使用。 在配置vue-cli中创建项目时,就可以直接选中vuex项,这样就不用做任何配置了(脚手架会自动帮我们完成的)。具体如下图示:

B75A81CC-F329-9E08-65B8-E320723039D1.png

这里我们主要说明第一种情况,在一个老项目中如何使用vuex,步骤如下:

1.首先安装vuex包,安装完之后开始配置
2.在src目录下创建一个文件夹store,在store文件夹中新建一个index.js文件
3.创建Vuex.store实例 :index.js中进行如下配置:

8AB2A0C6-1BC8-2705-5723-A337C18647EF.png

 4.向Vue实例注入store:main.js中进行如下配置: 

03B98263-1078-BE5E-F6F3-FF10E54A7B11.png

 5.配置完后就可以在任意组件中使用了 

在任意组件中,通过this.$store.state来获取公共数据,在模板中,则可以省略this而直接写成:{{$store.state.属性名}}

一、安装vuex
npm install vuex --save
二、创建store

在项目src目录下创建store目录,在store目录中创建index.js文件。写入一下内容:

import Vue from 'vue'
import Vuex from 'vuex'
 
// 挂在Vuex
Vue.use(Vuex)
 
// 创建Vuex对象
const store = new Vuex.Store({
    state:{
        // 存放的键值对就是所要管理的状态
        // 以key:value为例
        key : value,
    },
    mutations:{
        setKey(state, payload) {
            state.key = payload;
        }
    }
})
 
export default store
三、挂载store

在main.js中,添加代码:

import store from './store'

new Vue({
  el: '#app',
  router,
  store: store, //store:store 和 router一样,将我们创建的Vuex实例挂载到这个vue实例中
  components: { App },
  template: '<App/>'
})
四、在组件中使用

将需要使用的值写在computed中:

computed:{
    key() {
        return this.$store.state.key;
    }
}

如果在组件中使用v-model绑定computed中的值,需要在computed中定义set方法,如下:

computed:{
    key:{
        get(){
            return this.$store.state.key;
        },
        set(val){
            this.$store.commit('setKey', val);
        }
    }
}
五、在Vue组件中监听Vuex

在Vue组件中监听Vuex:

通过computed获取vuex中的状态值。

通过watch监听值的改变。

computed:{
    key(){
        return this.$store.state.key;
    }
},
watch:{
    key(val) {
        // 要做的操作
    }
}
收藏 (0)
评论列表
正在载入评论列表...
我是有底线的