vuex一些简单的用法

安装

npm install vuex --save

 

在使用Vuex前,我们先了解一下这几个东西:

state:一般情况下,我们在state里面定义需要共享的参数,它有点类似于Vue中的data

mutations:用来改变 store 中的状态,也就是说,你可以在mutations里面定义方法,用来修改state里面定义的某个参数的值

getters:计算属性,这个和Vue中的computed计算属性用法一致

 

创建Vuex实例,并且将它挂载到Vue中

首先在src目录下创建一个"store"文件夹,然后在"store"文件夹里面创建index.js文件,代码如下:

 

import Vue from 'vue'
import Vuex from 'vuex'
// 让Vuex在各个组件内都可以使用
Vue.use(Vuex)
const state = {
    city: '厦门'
}
// 创建Store实例
const store = new Vuex.Store({
  state,
})
export default store

 

 

在上面代码中,我们已经在"store"文件夹里面的index.js中创建了Vuex,如果要在Vue中使用,那么就的将Vuex挂载到Vue实例中,在项目入口文件main.js中引入并挂载即可。

import Vue from 'vue'
import App from './App'
import router from './router'
//引入store
import store from './store/index' 

Vue.config.productionTip = false
Vue.use(VueAwesomeSwiper)

new Vue({
  el: '#app',
  router,
  store,//放在Vue实例中
  components: { App },
  template: '<App/>'
})

 

在组件中使用Vuex

这时,就可以在组件上使用store了。在store/index.js文件中,我们在state中定义了一个city变量,那如何在组件中使用呢?直接通过this.$store.state.city即可。代码如下:

<template>
    <div class="my-header">
        <div class="left">
            <span class="icon iconfont">&#xe606;</span>
        </div>
        <div class="input">
            <span class="icon iconfont">&#xe607;</span>
            输入城市/景点/游玩主题
        </div>
        <router-link to="/city">
            <div class="right">
                {{this.$store.state.city}}
                <span class="icon iconfont">&#xe64a;</span>
            </div>
        </router-link>
    </div>
</template>

 

通过mutations修改Vuex状态,也就是修改上面代码中"city"的值

我们去store/index.js文件中添加一些代码,

 

import Vue from 'vue'
import Vuex from 'vuex'
// 让Vuex在各个组件内都可以使用
Vue.use(Vuex)
const state = {
    city: '厦门'
}

const mutations = {
    upCity (state,city) {
        state.city = city
    }
}

// 创建Store实例
const store = new Vuex.Store({
  state,
  mutations
})
export default store

 

 

然后通过"commit"方法来触发upCity函数,代码如下:

this.$store.commit('upCity','香格里拉') 

 

posted @ 2018-01-18 19:42  兔子先生i  阅读(238)  评论(0编辑  收藏  举报