vuex的安装和使用

1、安装
注意应安装和Vue对应的版本。
vue2安装命令:npm i vuex@3
vue3安装命令:npm i vuex@4
2、创建vuex文件
store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
    count: 0
}
const mutations = {
    PLUSE(status, val){
        state.count = val + 1
    }
}
const actions = {
    plusOne(context, val){
        context.commit('PLUSE', val)
    }
}

export default new Vuex.Store({state, mutations, actions})

3、添加vuex的引用
main.js

import Vue from 'vue'
import App from './App.vue'

import router from './router'

import store from './vuex/store'

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

4、应用vuex
Home.vue

<template>
    <div>
        <h1>Home页面</h1>
        <p>{{ counter }}</p>
        <el-button @click="plusOne">加一</el-button>
    </div>
</template>

<script>
export default {
    name: 'Home',
    data () {
        return {
            counter: 0
        }
    },
    methods: {
        plusOne () {
            this.$store.dispatch('plusOne', this.counter)
            this.counter = this.$store.state.count
        }
    }
}
</script>

5、功能
按“加一”按钮,显示的数据加1.

你可能感兴趣的:(Vue,Web,vue.js,vuex)