zoukankan      html  css  js  c++  java
  • Vue.observable

    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>
  • 相关阅读:
    【u026】花园(garden)
    【BZOJ 1040】[ZJOI2008]骑士
    【t100】汤姆斯的天堂梦
    【BZOJ 1038】[ZJOI2008]瞭望塔
    【t096】树的序号
    Java Web整合开发(82)
    2 HTML解析
    T3186 队列练习2 codevs
    T3185 队列练习1 codevs
    T1191 数轴染色 codevs
  • 原文地址:https://www.cnblogs.com/zxuedong/p/12834461.html
Copyright © 2011-2022 走看看