欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vuex的基本使用

程序员文章站 2024-02-28 12:15:46
...

Vuex是什么

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state),就是给其他组件调用共同数据的,具体参考官方讲解

搭建vue项目

终端运行命令 vue init webpack my-project
(前提有node.js环境和vue-cli环境)
如下是搭建好的vue项目目录和页面
Vuex的基本使用
Vuex的基本使用

引入Vuex

1、利用npm包管理工具,进行安装 vuex。在项目终端输入下边的命令就可以了。

 npm install vuex --save

2、在src目录下新建store.js文件,文件中引入我们的vue和vuex。

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

3、引入之后用Vue.use进行引用。

Vue.use(Vuex)

4、在main.js文件里引入store.js文件

import store from "./store";

5、Vue对象加入store对象

new Vue({
  el: "#app",
  store,
  router,
  components: { App },
  template: "<App/>"
});

6、store.js中用export default封装代码让外部使用,新建一个常量对象count

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

7、在components文件夹下新建 add.vue 文件,在App.vue中引入add.vue 组件

import add from "./components/add";
export default {
  name: "App",
  components: {
    add
  }
};

8、在add.vue中用$store.state.count直接调用store.js中count数据,add页面就可以读取到store.js中的count数据(其他组件引用store.js中数据的方法一样)

<template>
  <h1>{{$store.state.count}}</h1>
</template>

Vuex的基本使用
官方demo但是过于官方,对Vuex小白很不友好。

相关标签: Vuex vue.js