westore icon indicating copy to clipboard operation
westore copied to clipboard

组织自己的store可以使用这种方法

Open zwmmm opened this issue 6 years ago • 5 comments

a.js

export default  {
    data: {
        numa: 1,
        numb: 2
    },
    getA() {
        console.log('a');
    }
}

b.js

export default  {
    data: {
        numc: 3,
        numd: 4
    },
    getA() {
        console.log('b');
    }
}

store.js

import a from './a.js'
import b from './b.js'

const commonData = {
    commona: 'common'
}
function storeMixin(options) {
    let result = {
        data: commonData ,
    }
    for (let k in options) {
        let value = options[k];
        if (value.data) {
            result.data[k] = value.data
            delete value.data
        }
        Object.assign(result, value)
    }
    return result;
}

export default storeMixin({a, b})

根据page划分store, 不过函数名字就不能重复了

zwmmm avatar Sep 28 '18 06:09 zwmmm

最终返回的值是

{
    data: {
        a: {
            numa: 1,
            numb: 2
        },
        b: {
            numc: 3,
            numd: 4
        }
    },
    getA() {
        console.log('a');
    },
    getB() {
        console.log('b');
    }
}

zwmmm avatar Sep 28 '18 06:09 zwmmm

赞,不错~

dntzhang avatar Sep 28 '18 07:09 dntzhang

update的时候key应该怎么样呢 image 请问如何更新到roomStore里面的数据呢. image 然后wxml里面该如何绑定数据。我试了roomStore.xxx不行.直接xxx也不行呢. image

bili-jing avatar Aug 05 '19 07:08 bili-jing

update的时候key应该怎么样呢 image 请问如何更新到roomStore里面的数据呢. image 然后wxml里面该如何绑定数据。我试了roomStore.xxx不行.直接xxx也不行呢. image

仔细看下readme 第一个问题 数据更新 使用

this.store.data.a = 'a'
this.update()

在wxml中使用的数据需要现在page的data中声明(但是默认值要在store中设置)

{
  data: {
     a: null
  },
  onload() {
    this.store.data.a = 'a'
    this.update()
 }
}
<div>{{ a }}</div>

zwmmm avatar Aug 05 '19 07:08 zwmmm

@zwmmm 谢谢老哥。情况是 { data: { a: { numa: 1, numb: 2 }, b: { numc: 3, numd: 4 } }, getA() { console.log('a'); }, getB() { console.log('b'); } } a-page对应的data也应该是 a: { numa: 1, numb: 2 }, 是么. 然后wxml绑定即{{a.numa1}}

bili-jing avatar Aug 05 '19 08:08 bili-jing