1 状态共享
随着组件的细化,就会遇到多组件状态共享的情况,Vuex
当然可以解决这类问题,不过就像Vuex
官方文档所说的,如果应用不够大,为避免代码繁琐冗余,最好不要使用它,今天我们介绍的是vue.js 2.6新增加的Observable API ,通过使用这个api我们可以应对一些简单的跨组件数据状态共享的情况。
如下这个例子,我们将在组件外创建一个store
,然后在App.vue
组件里面使用store.js提供的store
和mutation
方法,同理其它组件也可以这样使用,从而实现多个组件共享数据状态。
首先创建一个store.js,包含一个store
和一个mutations
,分别用来指向数据和处理方法。
import Vue from "vue";
export const store = Vue.observable({
count: 0 });
export const mutations = {
setCount(count) {
store.count = count;
}
};
复制代码
然后在App.vue
里面引入这个store.js,在组件里面使用引入的数据和方法
<template>
<div id="app">
<img width="25%" src="./assets/logo.png">
<p>count:{
{count}}</p>
<button @click="setCount(count+1)">+1</button>
<button @click="setCount(count-1)">-1</button>
</div>
</template>
<script>
import { store, mutations } from "./store";
export default {
name: "App",
computed: {
count() {
return store.count;
}
},
methods: {
setCount: mutations.setCount
}
};
</script>
<style>
复制代码
你可以点击在线DEMO查看最终效果