国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

Vue局部組件數據共享Vue.observable()的使用

發(fā)布時(shí)間:2021-08-17 12:16 來(lái)源: 閱讀:0 作者:GGCoder 欄目: JavaScript 歡迎投稿:712375056

隨著(zhù)組件的細化,就會(huì )遇到多組件狀態(tài)共享的情況, Vuex當然可以解決這類(lèi)問(wèn)題,不過(guò)就像 Vuex官方文檔所說(shuō)的,如果應用不夠大,為避免代碼繁瑣冗余,最好不要使用它,今天我們介紹的是 vue.js 2.6 新增加的 Observable API ,通過(guò)使用這個(gè) api 我們可以應對一些簡(jiǎn)單的跨組件數據狀態(tài)共享的情況。

創(chuàng )建store對象

首先創(chuàng )建一個(gè) store.js,包含一個(gè) store和一個(gè) mutations,分別用來(lái)指向數據和處理方法。

//store.js
import Vue from 'vue';

export let store =Vue.observable({count:0,name:'李四'});
export let mutations={
    setCount(count){
        store.count=count;
    },
    changeName(name){
        store.name=name;
    }
}

把store對象應用在不同組件中

然后再在組件中使用該對象

//obserVable.vue
<template>
  <div>
    <h1>跨組件數據狀態(tài)共享 obserVable</h1>
    <div>
      <top></top>
      <bottom></bottom>
    </div>
  </div>
</template>

<script>
import  top  from './components/top.vue';
import  bottom  from './components/bottom.vue';
export default {
  name: 'obserVable',
  components: {
    top,
    bottom
  }
};
</script>

<style scoped>
</style>
//組件a
<template>
  <div class="bk">
    <span
      ><h1>a組件</h1>
      {{ count }}--{{ name }}</span
    >
    <button @click="setCount(count + 1)">當前a組件中+1</button>
    <button @click="setCount(count - 1)">當前a組件中-1</button>
  </div>
</template>
<script>
import { store, mutations } from '@/store';
export default {
  computed: {
    count() {
      return store.count;
    },
    name() {
      return store.name;
    }
  },
  methods: {
    setCount: mutations.setCount,
    changeName: mutations.changeName
  }
};
</script>
<style scoped>
.bk {
  background: lightpink;
}
</style>
//組件b
<template>
  <div class="bk">
    <h1>b組件</h1>
    {{ count }}--{{ name }}
    <button @click="setCount(count + 1)">當前b組件中+1</button>
    <button @click="setCount(count - 1)">當前b組件中-1</button>
  </div>
</template>
<script>
import { store, mutations } from '@/store';
export default {
  computed: {
    count() {
      return store.count;
    },
    name() {
      return store.name;
    }
  },
  methods: {
    setCount: mutations.setCount,
    changeName: mutations.changeName
  }
};
</script>
<style scoped>
.bk {
  background: lightgreen;
}
</style>

顯示效果

到此這篇關(guān)于Vue局部組件數據共享Vue.observable()的使用的文章就介紹到這了,更多相關(guān)Vue.observable() 數據共享內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

大屁股人妻女教师撅着屁股| 2021亚洲国产精品无码| JIZZJIZZ中国高潮喷水JIZJIZ| 亚洲国产精品成人久久| 无码精品尤物一区二区三区| 国产V综合V亚洲欧|