zoukankan      html  css  js  c++  java
  • 使用vite搭建vue3项目(六) 使用vuex进行状态管理

    vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

    安装

    npm install vuex@next --save

    直接使用

    this.$store.state.xxx

    首先在src目录下创建store文件夹,在其下创建index.ts

    import {createStore} from "vuex"
    
    const store = createStore({
        state() {
            return {num: 1,}
        }
    })
    
    export default store

     修改main.ts 

    import {createApp} from 'vue'
    import router from './router/index'
    import store from './store/index'   // 引入
    import i18n from './locales/index'
    import App from './App.vue'
    
    createApp(App)
        .use(store)   // 使用
        .use(router)
        .use(i18n)
        .mount('#app')

    修改App.vue

    <template>
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>学校:{{getSchool('北京')}}</div>
    <div>学校:{{getSchool('天津')}}</div>
    <div>num:{{$store.state.num}}</div>
    </template>

    <script lang="ts">
    import { defineComponent,ref} from "vue";
    import { useStore } from 'vuex'


    export default defineComponent({
    name: 'App',
    setup() {
    const store = useStore()
    let count = store.state.num;

    function getSchool(val: string) {
    count++
    store.state.num = count
    return val + '第' + count + '小学'
    }

    return {getSchool}
    }
    })
    </script>

    显示如图

  • 相关阅读:
    Spring spEL
    Spring 使用外部部署文件
    Spring 自动装配
    spring 属性配置细节
    hdu 1054 Strategic Game
    fzu 2037 Maximum Value Problem
    将博客搬至CSDN
    HDU 4714 Tree2Cycle
    HDU 1009 The Shortest Path in Nya Graph
    POJ 1942 Paths on a Grid 组合数的优化
  • 原文地址:https://www.cnblogs.com/zsg88/p/15669364.html
Copyright © 2011-2022 走看看