赞
踩
一、vuex(较大项目)
使用方法:占坑,网上很多
二、Observable API
随着组件的细化,就会遇到多组件状态共享的情况, 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 src="./assets/logo.png">
- <p>count: {{ count }}</p>
- <!-- <router-view/> -->
- <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
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
ps:代码案例来自公众号JavaScript
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。