自己制作一个网站需要什么软件,汕头新闻,前端一般怎样做网站,wordpress分类含有中文实现组件全局#xff08;数据#xff09;管理的一种机制#xff0c;可以方便的实现组件之间共享数据#xff0c;不同于上述三种传递值的方式。
可以把vuex当成一个store仓库#xff0c;可以集中管理共享的数据#xff0c;并且存储在vuex中的数据都是响应式的#xff0c…实现组件全局数据管理的一种机制可以方便的实现组件之间共享数据不同于上述三种传递值的方式。
可以把vuex当成一个store仓库可以集中管理共享的数据并且存储在vuex中的数据都是响应式的数据与页面同步。
一般情况下只有组件之间共享的数据才有必要存储到vuex中对于组件中的私有数据依旧存储在组件自身的data中。 注意如果你使用的是HBuilderX它已经内置了Vuex。如果你是使用npm或者yarn可以通过以下命令安装 安装vuex
npm install vuex --save 1、创建Vuex的store
在项目的src目录下创建一个store文件夹然后在该文件夹中创建一个index.js文件用于定义和配置Vuex store。 /* // 方式一import { createStore } from vuex;export default createStore({state() {return {count:0,// 定义一个名为 name 的状态//公共的变量存储数据这里的变量不能随便修改只能通过触发mutations的方法才能改变};},mutations: {increment(state) {// 定义一个名为 increment 的修改状态方法state.count;}//相当于同步的操作},actions: {increment({ commit }) {commit(increment);}//相当于异步的操作,不能直接改变state的值只能通过触发mutations的方法才能改变},getters: {count: (state) state.count},}); */
// 方式二 推荐
import Vuex from vuex;
import {LoginPostMethod} from /api/api.js;const store new Vuex.Store({state: {count:0,// 定义一个名为 name 的状态resToken: ,// 定义token//公共的变量存储数据这里的变量不能随便修改只能通过触发mutations的方法才能改变},mutations: {increment(state) { // 定义一个名为 increment 的修改状态方法state.count ;},setToken(state,token){// 定义一个名为 setToken 的修改状态方法console.log(state,state);console.log(token,token);state.resToken token.resToken;uni.setStorageSync(resToken, token.resToken);},setEmptyToken(state){// 定义一个名为 setEmptyToken 的修改状态方法console.log(emptyState,state);state.resToken ;uni.setStorageSync(resToken, null);},//相当于同步的操作},actions: {// 网络请求async logIn(context,apyload){console.log(context,context);console.log(apyload,apyload);const res await LoginPostMethod(apyload)console.log(执行成功,res)if(res.success){const token {resToken: res.token,}// 设置tokencontext.commit(setToken, token)}// 返回值return res;},//相当于异步的操作,不能直接改变state的值只能通过触发mutations的方法才能改变}})export default store 2、在main.js中引入store并使用 3.使用
import store from /store/index.js;//需要引入store***
export default{data(){return{}},methods:{addCountMethod() { // 定义一个名为 addMethod 的增加 count 的方法// 修改状态方法store.commit(increment);// 获取 state 中的 count 值const curcount store.state.count;console.log(curcount,curcount);}, setMethodOne(){// 直接调用/store/index.js mutations中定义的方法store.commit(setEmptyToken);},setMethodTwo(){// 调用/store/index.js 中logIn方法const result await store.dispatch(logIn, res)},}
}