Vuex的基本使用
- npm install vuex@next
- import { createStore } from "vuex";
-
- //调用函數創建仓库
- const store = createStore({
- state() {
- return {
- realman: '阿伦',
- };
- },
- });
-
- export default store;
- $store.state.xxx
- (1) 组件中定义一个方法,commit提交mutation方法
- changeMan(){
- this.$store.commit("changeMan")
- }
- (2) index.js里定义mutation
> - mutations:{
> - changeMan(state){
> - state.realman = "小叮当"
> - }
> - }
Vuex的state在组建中的computed写法
- import { mapState } from "vuex";
-
- export default {
- computed:{
- fullname(){
- return "大叮当"+"哆啦A梦"
- },
-
- ...mapState(["realman","age","name","sex"])
- },
- }
-
- ...mapState({
- sname: state => state.name,
- sage: state => state.age,
- })
getters的基本使用
- state() {
- return {
- bookPrice: 50,
- penPrice: 20,
- };
- },
- getters:{
- totalPrice(state,getters){//两个参数
- let totalPrice = state.bookPrice + getters.penPrcie;
- return totalPrice
- },
- penPrcie(state){
- return state.penPrice + 10;
- }
- }
- 总价值:{{ $store.getters.totalPrice }}
- getters里的方法可以return方法定义参数,在页面输入参数去调用
getters的computed写法
- import { mapState,mapGetters } from "vuex";
-
- ...mapGetters(['a','b']),
- ...mapGetters({
- cc: "a",
- dd: "b"
- })