怎样做的网站内网外网都能用,安徽智能网站建设推荐,做平面的素材网站,网络营销软文vuex的特点#xff1a;
多组件共享状态: 多个组件使用同一个数据 任何一个组件发生改变, 其他组件也要跟着发生相应的变化
安装vuex npm install vuex#xff1a;
创建实例#xff1a;
import Vuex from vuex
import Vue from vue
Vue.use(Vuex)const state {name : 张…vuex的特点
多组件共享状态: 多个组件使用同一个数据 任何一个组件发生改变, 其他组件也要跟着发生相应的变化
安装vuex npm install vuex
创建实例
import Vuex from vuex
import Vue from vue
Vue.use(Vuex)const state {name : 张三,age : 18
}
const mutations {// 更改 Vuex 的 store 中的状态的唯一方法是提交 mutationchangeName (state, params) {state.name params.name},changeAge (state, params) {state.age params.age}
}
const actions {// Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象因此你可以调用 context.commit 提交一个 mutationactionsChangeAge ( context, params) {context.commit(changeAge, params)}
}
const getters {// Getter 接受 state 作为其第一个参数doubleAge (state) {return state.age * 2}// 也可以使用箭头函数的简写// doubleAge: state state.age * 2
}const store new Vuex.Store({ // 创建全局状态管理的实例state, // 共同维护的全局状态mutations, // 处理数据的唯一途径, 修改state的数据只能通过mutationsactions, // 数据的异步操作处理getters // 获取数据并渲染
})// 导出并在main.js里面引用注册
export default store# 引入文件
import Vue from vue
import App from ./App.vue
import store from ./store/index
Vue.config.productionTip falsenew Vue({store, // 全局使用render: h h(App),
}).$mount(#app)# 模板templatedivh2组件/h2!-- 组件可以通过this.$store.state 获取store中的数据 --name: {{ this.$store.state.name }} brage: {{ this.$store.state.age }}button clickchange修改年龄/button/div
/template
script
export default {methods: {change () {// 此方法一般用于网络请求// dispatch: 调用actions里面的方法, 再让actions里面的方法// 通过commit 调用mutations里面的方法this.$store.dispatch(actionsChangeAge, { age: 120 })},changeName () {// 通过$store.commit直接调用store实例中mutation里面的方法// 参数1: 要调用mutation里面的方法名, 参数2: 要传输的数据this.$store.commit(changeName, { name: 宝宝, age: 19})}}
}
/script
----------------------------------------------------------------// 以载荷形式
store.commit(increment{amount: 10 //这是额外的参数
})// 或者使用对象风格的提交方式
store.commit({type: increment,amount: 10 //这是额外的参数
})dispatch含有异步操作数据提交至 actions 可用于向后台提交数据
this.$store.dispatch(isLogin, true);commit同步操作数据提交至 mutations 可用于读取用户信息写到缓存里
this.$store.commit(loginStatus, 1);state 存放基本数据
getters 从state基本数据派生出的数据(类似vue中的computed)
mutations Store中更改state数据状态的唯一途径
actions 通过dispatch触发actions, actions在通过commit触发mutations。一般用于处理异步操作
modules 模块化Vuex