美文网首页
Vue.observable 实现简单store管理

Vue.observable 实现简单store管理

作者: 0说 | 来源:发表于2019-05-23 15:44 被阅读0次

Vue.observable
使对象反应。在内部,Vue在data函数返回的对象上使用它。

返回的对象可以直接在渲染函数计算属性中使用,并在变异时触发适当的更新。它还可以用作简单场景的最小跨组件状态存储:

store.js

import vue from 'vue';
export const store =  vue.observable({count: 0});
export const mutation = {
  setCount( count ){
    store.count = count;
  }
}

应用组件:

<template>
  <div class="hello">
    <p @click="setCount(testCount + 1)">+</p>
    <p @click="setCount(testCount - 1)">-</p>
    <test />
    <p>{{testCount}}</p>
  </div>
</template>

<script>
import test from './test'
import { store,  mutation} from '@/store'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  components: {
    test
  },
  methods: {
    setCount: mutation.setCount
  },
  computed: {
    testCount(){
      return store.count
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

test组件

<template>
  <div>test{{testCount}}</div>
</template>
<script>
import { store } from '@/store';
export default {
  computed: {
    testCount(){
      return store.count
    }
  }
}
</script>
<style scoped>

</style>

相关文章

网友评论

      本文标题:Vue.observable 实现简单store管理

      本文链接:https://www.haomeiwen.com/subject/odcbzqtx.html