vue 之更新了vuex store里面的 数据后 界面视图没有同步更新(动态数据)_vue中读取store里的数据不同步-CSDN博客

store  state

/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 里面才能同步更新视图

ps:写的不对的希望大家指出来,谢谢大佬!结论只是我目前现象看来的,具体的还有待深入测试


原网址: 访问
创建于: 2023-10-08 11:20:59
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论