zoukankan      html  css  js  c++  java
  • Vuex的基本使用

    1 基本介绍

    Vuex是一个专为Vue.js应用程序开发的状态管理器。

    2 应用场景

    在多个组件里共享的状态,比如用户的登录状态,名称、头像、地理位置、购物车等。

    3 安装方式

    npm install vuex --save

    4 代码部署

    4.1 srcstoreindex.js

    import Vue from "vue";
    import Vuex from 'vuex'
    //1 安装插件
    Vue.use(Vuex)
    
    //2 创建对象
    //Vuex有一个Store类
    const store = new Vuex.Store({
      //保存状态
      state:{
        counter:999
      },
      mutations:{
        //方法 默认带state参数
        increment(state){
          state.counter++
        },
        decrement(state){
          state.counter--
        }
      },
      actions:{
    
      },
      getters:{
    
      },
      modules:{
    
      }
    })
    //3 导出store对象
    export default store

    4.2 srcmain.js

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import store from "./store";
    
    
    Vue.config.productionTip = false
    
    
    new Vue({
      router,
      store,
      render: function (h) { return h(App) }
    }).$mount('#app')

    4.3 srcApp.vue

    <template>
      <div id="app">
        <h2>message:{{message}}</h2>
        <h5>counter:{{counter}}</h5>
        <h5>counter:{{$store.state.counter}}</h5>
        <h5>通过@click="counter++修改"</h5>
        <button @click="counter++">+</button>
        <button @click="counter--">-</button>
        <h5> 通过 @click="$store.state.counter++修改 官方不建议这样来改"</h5>
        <button @click="$store.state.counter++">+</button>
        <button @click="$store.state.counter--">-</button>
        <h5>通过mutations修改</h5>
        <button @click="addition">+</button>
        <button @click="subtraction">-</button>
    
       <!-- <router-view/>-->
        <hello-vuex></hello-vuex>
      </div>
    </template>
    <script>
      import HelloVuex from "./components/HelloVuex";
    
      export default {
        name:'App',
        components:{
          HelloVuex
        },
        data(){
          return {
            message:'我是app组件',
            counter:0
          }
        },
        methods:{
          addition(){
            this.$store.commit('increment')
          },
          subtraction(){
            this.$store.commit('decrement')
          }
        }
      }
    </script>
    <style>
    
    </style>

    安装Devtools插件

    代码下载

    链接:https://pan.baidu.com/s/1rax0wgZg895GmvQ5ryZTJQ
    提取码:fcz3

  • 相关阅读:
    Elasticsearch入门系列(一)
    清楚Chrome缓存
    解决IIS启动站点报错
    Input type="file"上传文件change事件只触发一次解决方案
    本地计算机上的XXX服务启动后停止,某些服务在未由其它服务或程序使用时将自动停止
    SQL Server Datetime类型为NULL不能用ISNULL(datetime,' ')来判断,会导致1900-01-01
    浏览指南
    谁发明的c++
    c++的用处
    不一样的二叉树遍历(小学生都会)
  • 原文地址:https://www.cnblogs.com/polax/p/13220675.html
Copyright © 2011-2022 走看看