关于vuex的demo
技术:vuex,vue
首先下载vuex
创建store文件夹下index.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); const store = new Vuex.Store({ state: { demo: { name: 'Demo', age: 22, } }, getters: { getttersName(state) { return state.demo.name + "---get" }, getttersAge(state) { return state.demo.age + "---get" } }, mutations: { // 定义方法改变数据 setName(state, name) { state.demo.name = name }, setAge(state, age) { state.demo.age = age } }, actions: { // 提交dispch actionName(context, name) { console.log('ss') return context.commit('setName', name); }, actionAge(context, age) { return context.commit('setAge', age); } } }) export default store;
在main.js文件中引入
import Vue from 'vue' import App from './App' import router from './router' import store from './store' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
在使用的页面.vue文件
<template> <div> <h1>wowoow</h1> <h2>{{getttersName}}</h2><button @click="setName('woshi')">测试</button> <h2>{{getttersAge}}</h2> </div> </template> <script> import { mapState, mapGetters, mapMutations, mapActions } from "vuex"; export default { name: "Demo", data() { return {}; }, computed: { ...mapGetters(["getttersName", "getttersAge"]) }, methods: { ...mapMutations({ setName: "setName", setAge: "setAge" }), ...mapActions({ actionName: "actionName", actionAge: "actionAge" }) } }; </script> <style> </style>
集思广益,仅供学习,侵权即删!!