vue使用observable组件传值

demo目录

Parent.vue
Child.vue
store.js

store.js

import Vue from 'vue'

export const store = Vue.observable({
    count: 0
})

export const mutations = {
    addCount () {
        store.count = store.count + 1
    },
    minusCount () {
        store.count = store.count - 1
    }
}

Parent.vue

<template>
    <div>
        <p>parent: {{ store.count }}</p>
        <button @click.prevent="handleAdd">父组件 - 加</button>
        <button @click.prevent="handleMinus">父组件 - 减</button>
        <Child></Child>
    </div>
</template>

<script>
import { store, mutations } from './store'
import Child from './Child'
export default {
    name: 'ParentPage',

    components: {
        Child
    },

    data () {
        return {
            store: store
        }
    },

    methods: {
        handleAdd () {
            mutations.addCount()
        },
        handleMinus () {
            mutations.minusCount()
        }
    }
}
</script>

Child.vue

<template>
    <div>
        <p>child: {{ store.count }}</p>
        <button @click.prevent="handleAdd">子组件 - 加</button>
        <button @click.prevent="handleMinus">子组件 - 减</button>
    </div>
</template>

<script>
import { store, mutations } from './store'
export default {
    name: 'ChildPage',

    data () {
        return {
            store: store
        }
    },

    methods: {
        handleAdd () {
            mutations.addCount()
        },
        handleMinus () {
            mutations.minusCount()
        }
    }
}
</script>

Vue-observable

推荐阅读更多精彩内容