Vuex——基本使用

xiaoxiao2025-11-25  9

1. 安装

npm i vuex -S

2.vue的基本使用流程

   一.新建store的js文件

         1.引入模块

import Vuex from 'vuex'

         2.注册模块

import Vue from 'vue' Vue.use(Vuex)

         3. 声明实例并且返回实例

export default new Vuex.Store({ state: { count: 0 }, }

          4.设置改变状态的方法

export default new Vuex.Store({ state: { count: 0 }, mutations: { set_count (state, num) { state.count = num } } }

      二、main.js文件

            1.引入实例

import store from './common/js/store'

            2.注册实例(全局使用)

// 方法一 Vue.prototype.$store = store // 方法二 /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })

 

     三、*vue文件

            1.使用计算属性实时监听调用实例的状态

computed: { count () { return this.$store.state.count }, }

             2.在mounted中调用改变状态的方法

mounted () { let i = 1 setInterval (() => { this.$store.commit('set_count', i++) }, 1000) }

            3. 调用count计算属性,测试是否成功

<div>{{count}}</div>

 

转载请注明原文地址: https://www.6miu.com/read-5040013.html

最新回复(0)