怪物奇妙物语

宇宙无敌超级美少男的怪物奇妙物语

首页 新随笔 联系 管理
  822 随笔 :: 0 文章 :: 2 评论 :: 16万 阅读

前言

基于vuex的一个计数器,熟悉项目的搭建过程.

普通的计数器

文件目录

vuex-learn.lnk

输出效果

image-20220402200741509

Vuex实现计数器

  1. 这个计数器中,HelloWorld.vue , IamFine.vue,共用一个来自vuex中的数据.

安装Vuex

image-20220402210659744

创建store

  1. 在src下创建一个store文件夹
  2. 然后创建一个store.js文件

引入并使用

image-20220402214232565

创建一个store

image-20220402214252718

将store导出

  1. 为的是在main.js注册store,这样才能在各个组件中使用

image-20220402214341105

import Vue from 'vue';
// 引入Vuex
import Vuex from 'vuex';
// 使用Vuex
Vue.use(Vuex);
// 创建一个store
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
},
},
});
export { store };

报错

  1. 出现类似的报错 xxx.store is not a constructor

  2. 重点看这个报错的后半部分,store不是构造器,所以不能new Vuex.store()直接报错

  3. 正确的创建new Vuex.Store()

此错误是由于Vuex创建Store的时候写成了小写S才导致报错。

控制台错误信息:

img

解决方法:

注册store

  1. main.js中引入注册store

引入并注册store

import Vue from 'vue';
import App from './App.vue';
// 注册vuex中store
import { store } from './store/store';
Vue.config.productionTip = false;
new Vue({
render: (h) => h(App),
store,
}).$mount('#app');

使用store

  1. HelloWord.vue和IamFine.vue组件中使用store

vue组件中直接使用

image-20220402214741552

<template>
<div class="hello">
<h1 class="text">{{ this.$store.state.count }}</h1>
<div class="button">
<button @click="increment">+</button>
<button @click="decrement">-</button>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
num: 0,
};
},
methods: {
increment: function () {
this.$store.commit('increment');
},
decrement: function () {
this.$store.commit('decrement');
},
},
};
</script>

文件目录

计数器-vuex实现.lnk

输出效果

  1. 两个兄弟组件共享vuex中的数据,所以加加减减会同步显示

image-20220402214052863

posted on   超级无敌美少男战士  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示