vuex简单cdn版

<!DOCTYPE html>
<html>
<head>
  <title>Vuex CDN Example</title>
  <script src="https://unpkg.com/vue@3.2.20/dist/vue.global.js"></script>
  <script src="https://unpkg.com/vuex@4.0.2/dist/vuex.global.js"></script>
</head>
<body>
  <div id="app">
    <!-- Your Vuex example goes here -->
  </div>

  <script>
    // 创建一个 Vuex 实例
    const store = Vuex.createStore({
      state() {
        return {
            msg:11,
          count: 0
        }
      },
      mutations: {
        increment(state) {
          state.count++;
        },
        jian(state){
                 state.msg--;
        }
      },
      actions: {
        incrementAsync({ commit }) {
          setTimeout(() => {
            commit('increment');
          }, 1000);
        }
      },
      getters: {
        doubleCount(state) {
          return state.count * 2;
        }
      }
    });
  
    // 创建 Vue 应用程序
    const app = Vue.createApp({
      computed: {
        count() {
          return this.$store.state.count;
        },
        doubleCount() {
          return this.$store.getters.doubleCount;
        },
    msg(){
          return this.$store.state.msg;  
        }
      },
      methods: {
        dojian(){
     this.$store.commit('jian');
        },
        increment() {
          this.$store.commit('increment');
        },
        incrementAsync() {
          this.$store.dispatch('incrementAsync');
        }
      },
      template: `
        <div>
          <p>Count: {{ count }}</p>
          <p>Double Count: {{ doubleCount }}</p>
          <p>{{msg}}</p>
          <button @click="increment">Increment</button>
          <button @click="incrementAsync">Increment Async</button>
          <button @click="dojian">减</button>
        </div>
      `
    });

    app.use(store); // 注册 Vuex 实例

    app.mount('#app'); // 挂载应用程序
  </script>
  
</body>
</html>

1.创建应用实例Vue.createApp(),创建vuex实例 Vuex.createStore()

2.使用state()定义数据类似于 vue实例里的data

3.在mutations里定义方法,可以操作state里的数据,类似于vue的 methods()

4.在actions里执行异步操作

5.vuex的核心部分:

  1. State(状态):用于存储应用程序的状态数据。在 Vuex 中,状态存储在一个单一的状态树中,作为唯一的数据源。

  2. Getters(获取器):用于从状态中派生出新的数据,类似于计算属性。Getters 可以对状态进行包装和处理,以便在组件中使用。

  3. Mutations(变更):用于修改状态的方法。Mutations 是同步的操作,用于改变状态的值。每个 Mutation 都有一个字符串类型的事件类型和一个处理函数,通过提交 Mutation 来触发状态的变更。

  4. Actions(动作):用于处理异步操作和复杂的业务逻辑。Actions 可以包含多个异步操作,可以触发多个 Mutation 来修改状态。Actions 通过提交 Action 来触发异步操作。

  5. Modules(模块):用于将大型应用程序的状态拆分为多个模块。每个模块都有自己的状态、获取器、变更和动作,可以相互组合和嵌套。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值