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

  • 相关阅读:
    【JavaScript】关于javascript原型的深入理解
    【JavaScript】关于JS中的constructor与prototype
    【JavaScript】关于prototype
    【JavaScript】重温Javascript继承机制
    【JavaScript】新浪微博ajax请求后改变地址栏url,但页面不跳转的方案解析
    【JavaScript】JavaScript函数的参数
    【JavaScript】页面加载性能优化
    HTML5 修改浏览器url而不刷新页面
    【339】matplotlib based on python3
    【338】Pandas.DataFrame
  • 原文地址:https://www.cnblogs.com/polax/p/13220675.html
Copyright © 2011-2022 走看看