分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

JS——vuex 基本使用

发布时间:2023-09-06 02:03责任编辑:赖小花关键词:暂无标签

父子组件通信是传递私有数据,非父子组件通信传递的是共享数据,对共享数据进行管理可以帮助我们对全局状态进行统一管理

vuex 安装

npm install vuex --save

vuex 挂载

import Vuex from ‘vuex‘Vue.use(Vuex)

store 创建

var store = new Vuex.Store( ???state : { ???????count : 0 ???}, ???mutations:{ ???????})

加载到 vue 实例

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

访问 store 数据

<span>组件1:</span><input type=‘text‘ v-model=‘$store.state.count‘>

改变 store 数据

直接操作 $store.state.count 是不被推荐的,store 提供了一个操作 count 值的接口 motations

// 仓库中定义方法,方法的第一个参数永远是state,类似过滤器var store = new Vuex.Store({ ?state: { ???count: 0 ?}, ?mutations: { ???add(state) { ?????state.count++ ???} ?}})
// 组件通过commit方法进行调用export default { ?methods: { ???add() { ?????this.$store.commit("add"); ???} ?}};

调用接口并传参

commit 方法可以使组件改变共享数据,同时也可以传入参数,但是限制只能传入一个自己自定义的参数,所以在传入参数数据量大的情况下推荐使用对象传参

// 形式如下this.$store.commit("add", obj)

store 过滤器

这种叫法不准确,但是在形式上,store 提供的 getters 接口最后在结果上确实很像过滤器

var store = new Vuex.Store({ ?state: { ???count: 0 ?}, ?mutations: { ???add(state) { ?????state.count++ ???}, ???remove(state, num) { ?????state.count = state.count - (num.one + num.two) ???} ?}, ?getters: { ???show(state) { ?????return "加工一下 state 数据:" + state.count ???} ?}})

需要注意的是,getters 接口在也很类似于 computed,因为 state 的值只要发生变化,就会触发 getters 方法

JS——vuex 基本使用

原文地址:https://www.cnblogs.com/cnloop/p/9277809.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved