首页 > 其他 > 详细

Vue.observable

时间:2020-05-06 10:38:43      阅读:61      评论:0      收藏:0      [点我收藏+]

Vue.observable API 的使用

 

1.介绍如果项目不是足够大的话,为避免代码繁琐冗余,最好不要使用它。Vue.observable 是vue2.6版本新增的,可以实现一些简单的跨组件数据状态共享

// 创建store目录,store目录下创建index.js

import Vue from ‘vue‘

export const store = Vue.observable({
  count: 0,
  name: ‘李四‘
})

export const mutations = {
  setCount (count) {
    store.count = count
  },
  changeName (name) {
    store.name = name
  }
}


// 在组件中使用

<template>

    <div class="container">

      <button @click="setCount(count+1)">count++</button>

    </div>

</template>

<script>

import { store, mutations } from ‘@/store/index‘

export default {

    computed: {
        
        // 如果store中的数据发生变化重新计算
        count () {
          return store.count
        },

        name () {
          return store.name
        }
     },

    methods () {
        
        // 将store中的mutations方法赋值拿到
        setCount: mutations.setCount
    }
}

</script>
// 或者可以绑定到Vue的原型上

// store/index.js

import Vue from ‘vue‘

const store = {

  state: Vue.observable({
    count: 0,
    name: ‘李四‘
  }),

  mutations: {
    setCount (count) {
      store.state.count = count
    },
    changeName (name) {
      store.state.name = name
    }
  }

}

export default store


// 在组件中使用

<script>

export default {

  created () {

    // 通过this.store来调用
    console.log(this.store)
  }
}

</script>

 

Vue.observable

原文:https://www.cnblogs.com/zxuedong/p/12834461.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!