/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; 100%; } </style>
刚开始是没有放到computed 里面的(被我注释掉的部分) 视图没有同步更新 后来改成来以上代码就可以更新啦
结论:
1.本组件内data的数据和prop传递过来的数据能同步双向绑定和更新视图
2.vuex 中store的数据需要放到computed 里面才能同步更新视图
转自:https://blog.csdn.net/wangshang1320/article/details/98871252