使用Vuex实现最简易的计数功能

在Vue中,组件可以分为数据和视图两个部分,数据更新时试图也会随之更新,在视图中也可以绑定一些时间用于触发methods里指定的方法,从而改变数据、更新视图等操作,但是传统的Vue只能在本组件控制其他的组件就没有办法独去或修改,而Vuex就弥补了这个缺点,可以做到跨组件共享数据,话不多说直接操作。

1、Vuex是一个插件首先需要安装Vuex(所有npm的地方都可以换成cnpm将不再叙述)

npm install vuex --save

然后在Vue项目下的src文件夹中创建store文件夹意思意思为数据库,并在store下新建index.js 如图所示:

 内部代码如下:

复制代码
import Vue from 'vue';
import Vuex from 'vuex';//引入Vuex插件

Vue.use(Vuex);//调用Vue.use()方法使用

export default new Vuex.Store({
    //state存放所有的共享数据
    state:{
        count:0
    },
    //状态的变化
    mutations:{
        increment(){
            this.state.count++;
        },
        decrement(){
            this.state.count--;
        }
    }
});
复制代码

接着需要在main.js中引入store数据源,并在Vue实例中使用,main.js的代码如下:

复制代码
import Vue from 'vue'
import home from './components/counter.vue'
import router from './router'
import store from './store/index'//引入刚才写的index.js文件

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { home },
  template: '<home/>'
});
复制代码

main.js配置也结束了,接下来就是如何在实例当中使用了,在index.js中已经写了increment方法和decrement方法,接下来在实例中去使用,代码如下:

复制代码
<template>
    <div class="page">
        <p>{{count}}</p>
        <button @click="increment">+1</button>
        <button @click="decrement">-1</button>
    </div>
</template>
<script>
export default {
    data() {
        return {}
    },
    computed:{
        count(){
            return this.$store.state.count;
        }
    },
    methods: {
        increment(){
            //改变store中的状态唯一途径就是显式的提交
            this.$store.commit("increment");
        },
        decrement(){
            this.$store.commit("decrement");
        }
    },
}
</script>
复制代码

 

posted @   是小杰哦  阅读(109)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示