我试图用VueJS上传文件。 将文件添加到输入字段时,它将被缓冲并保存在vuex存储中。
我肯定状态更新,这显示在vue-devtool中,我添加了一个按钮来检查它。
然而,DOM不会在状态更改时重新呈现。我用缓冲区数组和常规字符串尝试了它。 (当我点击vue-dev工具中的提交按钮时,它会更新dom)
请参阅此屏幕截图以了解该问题(这是在选择文件并单击"控制台日志状态"按钮后)。 Demonstration
组件
<template>
<div id="home">
<h3>Upload Book (pdf)</h3>
<form v-on:submit="">
<input v-on:change="captureFile" type="file" placeholder="Select file..." />
<button type="submit">Upload</button>
<p>
<button v-on:click="consoleLog">Console log state</button>
{{filebuffer}}
</p>
</form>
</div>
</template>
<script>
export default {
name: 'home',
computed: {
filebuffer () {
return this.$store.state.fileBuffer
}
},
methods: {
captureFile (event) {
let file = event.target.files[0]
let reader = new window.FileReader()
reader.readAsArrayBuffer(file)
reader.onloadend = () => {this.$store.dispatch('loadBuffer', reader)}
},
consoleLog () {
console.log(this.$store.state.fileBuffer)
}
}
}
</script>
商品
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
Vue.use(Vuex)
export const store = new Vuex.Store({
strict: true,
state,
mutations: {
saveBuffer (state, payload) {
state.fileBuffer = 'this will not update on the DOM'
console.log('saveBuffer committed', payload)
}
},
actions: {
loadBuffer ({commit}, payload) {
let buffer = Buffer.from(payload.result)
commit('saveBuffer', buffer)
}
}
})
答案 0 :(得分:1)
您需要使用Getters。
computed: {
filebuffer () {
return this.$store.getters.filebuffer;
}
}
并在商店文件
内import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex)
// State
const state = {
fileBuffer : '',
}
// Mutate the State
const mutations = {
saveBuffer (state, value) {
state.fileBuffer = value
}
// Access The State
const getters = {
fileBuffer : state => {
return state.fileBuffer
}
}
const actions = {
loadBuffer ({commit}, payload) {
let buffer = Buffer.from(payload.result)
commit('saveBuffer', buffer)
}
}
const module = {
state,
getters,
mutations,
actions
};
export default module;
希望这有助于解决您的问题。