vue-cli vuex的使用

参考官网网址:vuex

1.安装vuex

npm install vuex --save

2.在src文件夹下创建store文件夹 |文件store/index.js,并在index.js中引入vuex

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

Vue.use(Vuex)

// 导出实例对象
export default new Vuex.Store({
    state:{
        city:'上海'
    },
    mutations:{
        render(state,city){
          state.city=city;
        }
    }
})

3.在main.js中引入

import store from './store' 

// 插入根实例
new Vue({
  el: '#app',
  router,  
  store,  // 插入store
  components: { App },
  template: '<App/>'
})

4.在组件中调用

// dom元素中调用
<el-button>{{this.$stroe.state.city}}</el-button>

<el-button type="success" v-for="(item,index) of list" :key="index" @click="changeCity(item.city)">{{item.city}}</el-button>

// 在js中调用
<script>
    export default {
        data(){
            return {
                list:[{
                    city:'上海'
                },{
                    city:'北京'
                },{
                    city:'杭州'
                }]
            }
        },
        methods: {
            changeCity(city){

               // 执行mutations中的方法使用commit(函数名,参数)
               this.$store.commit('render',city);

              // 路由跳转
               this.$router.push('/');
            }
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/weixin_39907729/article/details/81539752
今日推荐