VUE进阶 - observable

2020-04-26  本文已影响0人  wyc0859

observable可以用作简单场景的最小跨组件状态存储
和provide/inject一样,也可以向其所有子孙后代调用,当更多是用于状态存储

QQ截图20200426225432.png

新建store.js

import Vue from 'vue';
export let store =Vue.observable({count:0,sex:'男'});
export let mutations={
    setCount(count){
        store.count=count;
    },
    setSex(sex){
        store.sex=sex;
    }
}

index页面

<template>
    <view class="content">
        <p @click="setCount(testCount + 1)">+</p>
        <p @click="setCount(testCount - 1)">-</p>
        <test />
        <p>页面:{{testCount}}</p>
    </view>
</template>

<script>
    import test from './test'
    import { store,  mutation} from '@/store'
    export default { 
      components: {
        test
      },
      methods: {
        setCount: mutation.setCount
      },
      computed: {
        testCount(){
          return store.count
        }
      }
    }
</script> 

test组件

<template>
  <div>test组件
   <bb></bb>
  </div>
</template>
<script> 
import bb from './bb'
export default {
    components: {
      bb
    }
}
</script>

bb组件

<template>
    <view>
       bb组件:{{testCount}}
    </view>
</template>

<script> 
    import { store,  mutation} from '@/store'
    export default { 
         computed: {
           testCount(){
             return store.count
           }
         }
    }
</script> 
上一篇下一篇

猜你喜欢

热点阅读