vue:vuex store里面的數據更新后,如何在頁面同步更新


/detail/index.js

const state = {
    id:0,
    playUrl:'b'
};
const getters = {};
const actions = {};
const mutations = {
    setPlayUrl(state,url){
        state.playUrl = url;
        // state.url = url;
    }
};
export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations

index.js

import Vue from 'vue';
import Vuex from 'vuex';
import Detail from './songDetail/index'
 
 
Vue.use(Vuex);
 
const state = {};
const actions = {};
const mutations = {};
const store = new Vuex.Store({
    modules: {
        detail:Detail
    },
    actions,
    state,
    mutations
});
export default store;

pageA:

觸發mutation:

_this.$store.commit('detail/setPlayUrl',data.data.data);//存vuex
 

pageB:

展示數據:

<template>
    <div class="bottom">
        {{a}}
        <audio v-bind:src="getPlayUrl" controls="controls">
            Your browser does not support the audio element.
        </audio>
    </div>
</template>
<script>
    export default {
        name: "index",
        data(){
            return {
                // url:this.$store.state.detail.playUrl,  //如果這樣寫的話會更新不了
                a:'1',    //這個在本組件里面的數據就可以更新 這個a 在created生命周期后三秒改變值就可以更新視圖
            }
        },
        computed:{
//這里需要把store 動態的數據放到computed里面才會同步更新 視圖
            getPlayUrl(){
                return this.$store.state.detail.playUrl
            }
        },
        created() {
            // console.log('url',this.url);
            let _this = this;
            setTimeout(function () {
                _this.a = 10;
            },3000)
        }
    }
</script>
 
<style scoped>
    .bottom{
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
    }
</style>

剛開始是沒有放到computed 里面的(被我注釋掉的部分) 視圖沒有同步更新 后來改成來以上代碼就可以更新啦

結論:

1.本組件內data的數據和prop傳遞過來的數據能同步雙向綁定和更新視圖

2.vuex 中store的數據需要放到computed 里面才能同步更新視圖

轉自:https://blog.csdn.net/wangshang1320/article/details/98871252

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM